MySQLdb - insert value of a variable in the database

1

I am experiencing problems when trying to insert the values of my variables into the database I am trying to do as follows

import MySQLdb

id = 4
idade = 18
nome = 'cebolinha'
email = '[email protected]'

db = MySQLdb.connect("localhost","devel","********","Cadastro")
cursor = db.cursor()
sql = 'INSERT INTO usuarios(id, idade, nome email) VALUES (id, idade, nome, email)'
cursor.execute(sql)
cursor.fetchone()
db.commit()
db.close()

When I go to see the database, it is not inserting the values of my variables and neither does it return any errors.

NowwhenIrunthescriptthiswayit'sworking

importMySQLdbdb=MySQLdb.connect("localhost","devel","********","Cadastro")
cursor = db.cursor()
sql = 'INSERT INTO usuarios(id, idade, nome email) VALUES (3, 17, "daniel", "[email protected]")'
cursor.execute(sql)
cursor.fetchone()
db.commit()
db.close()

remembering that I'm using the python MySQLdb module

    
asked by anonymous 10.06.2016 / 18:14

2 answers

2

You need to pass the values of the variables inside the insert. By doing this VALUES (id, idade, nome, email) you are passing the literals ( id , idade , nome , email ) and not the values of the variables.

Change this

sql = 'INSERT INTO usuarios(id, idade, nome, email) VALUES (id, idade, nome, email)'

for

sql = 'INSERT INTO usuarios(id, idade, nome, email) VALUES (%s, %s, %s, %s)'

sql_data = (id, idade, nome, email)

And when it's time to run, do

cursor.execute(sql, sql_data)
    
10.06.2016 / 18:23
0

There must have been some mistake. In the insert insert, a comma is missing. sql = 'INSERT INTO usuarios(id, idade, nome email) VALUES (3, 17, "daniel", "[email protected]")'

And I think it's just a comma between name and email

    
10.06.2016 / 20:21