Mysqldb - insert value of a variable in the database

Asked

Viewed 2,607 times

1

i am facing problems while 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 in the database is not entering the values of my variables and this returns me no error

now when I run the script this way it’s working

import MySQLdb

db = 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()

recalling that I am using the python Mysqldb module

2 answers

2


You need to pass the values of the variables within 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 execute, do it

cursor.execute(sql, sql_data)
  • didn’t work no :(

  • Nothing happens? Does not generate any error?

  • return me this error query = query % db.literal(args) Typeerror: not enough Arguments for format string

  • Missing a comma between name and email, I edited the answer.

  • Jbueno: either the string is marked as positional arguments (%s,) and you use a sequence with the data (tuple, list, etc...) OR you use a dictionary and mark the values by name in the string " ... %(nome)s, %(idade)s - In your answer you try to input the data from a dictionary into sequential markings. This would not even work since dictionaries do not preserve the order of insertion of key/value pairs.

  • 1

    You’re right, I ended up mixing the two forms, lacked coffee (and attention) at that time. I will edit the reply, thanks for warning @jsbueno

Show 1 more comment

0

Probably there must have been an error. In the call Insert into, ta missing a comma. sql = 'INSERT INTO usuarios(id, idade, nome email) VALUES (3, 17, "daniel", "[email protected]")'

And I guess you just put a comma between name and email

Browser other questions tagged

You are not signed in. Login or sign up in order to post.