SQL statement fails through mysqldb.query in Python

安稳与你 提交于 2019-12-25 16:44:54

问题


I am trying to pass a query through my script, but i get a SQL error. Running the same sql statement in Heidisql works fine.

My question is: - What am I doing wrong?

error message

_mysql.connection.query(self, query) _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Gabrielsen)' at line 1")

Python script where Database is the correct connection to database

F="Gunnar Gabrielsen"
Database.query('INSERT INTO documents (name) values (' + F + ');')
i=Database.query('SELECT * from documents;')
print(i)

Python version:Python 3.4

Module:Mysqldb

DB:MariaDB


回答1:


You haven't put quotes around your value.

But you should never do it this way anyway. Quite apart from the quoting problem, you are opening yourself to sql injection attacks.

Use a parametrised query instead:

cursor.execute('INSERT INTO documents (name) values (%s)',  (F,))



回答2:


You have generated this:

INSERT INTO documents (name) values (Gunnar Gabrielsen);

What you need is

INSERT INTO documents (name) values ("Gunnar Gabrielsen");

But, without escaping or parameterizing, you are opening your code (and system) up to "sql injection" and other hacking.



来源:https://stackoverflow.com/questions/44209902/sql-statement-fails-through-mysqldb-query-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!