sql syntax error in mysql database with python 3

0

In my mysql project with python, when trying to modify a field of the table, the sequence sql generates error and I do not understand why. I accept the name change but when I enter the new price the error arises. The Cod element is the primary key of my table.

This is my code :

sql="update productos set Nombre='"+nombre+"'Precio='"+precio+"' where Cod="+cod    
mysql.connection.query(self, query)

And the error that launches:

  

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server   version for the right syntax to use near 'Price =' 120 'where Cod = 1' at   line 1 ")

    
asked by Jsierra2017 05.07.2017 в 19:48
source

2 answers

0

You must separate each field with a comma, in your case you want to update Name and Price, that is, between these two a comma goes.

  

NOTE: In case your Price is a type of whole data, it should not have single quotes.

sql="update productos set Nombre='"+nombre+"', Precio="+precio+" where Cod="+cod+"
    
answered by 05.07.2017 / 20:18
source
0

One suggestion, the way you are executing your query is insecure. Imagine that your variable nombre contain a statement to delete a table using a DROP TABLE . This is known as SQL injection .

Instead of executing your query that way, I recommend doing it using cursors and parameters. I'm not sure about the MySQL library you're using but basically it would be something like this:

connection = mysql.connector.connect(...)
cursor = connection.cursor()
query = '''
    UPDATE productos 
    SET Nombre=%s, Precio=%s 
    WHERE Cod=%s
'''
params = (
    nombre,
    precio,
    cod
)
cursor.execute(query, params)

Not only is it safer, it is also more readable.

    
answered by 07.07.2017 в 18:49