4

我正在尝试使用 python 和 MySQLdb 库将 url 添加到 mysql 中的文本行,但是当我运行我的代码时,它说我的 sql 语法中有错误。你能告诉我我做错了什么吗?

这是我的代码:

import MySQLdb as mdb
connection = mdb.connect("Localhost", "root", "", "db")
cursor = connection.cursor()
url = mdb.escape_string("http://www.google.com")
cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,))

这是错误:

Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 551, in __bootstrap_inner
self.run()
File "E:\prospector\webworker.py", line 77, in run
cursor.execute("INSERT INTO index(url) VALUES('%s')", (url_t,))
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in execute
self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
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 'index(url) VALUES('http://www.google.com/')' at line 1")
4

1 回答 1

3

我能够像这样复制您的问题:

mysql> create table `index` (url varchar(50));
Query OK, 0 rows affected (0.05 sec)

mysql> insert into index(url) values ('http://www.google.com');
ERROR 1064 (42000): 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 'index(url) values ('http://www.google.com')' at line 1

mysql> insert into `index`(url) values ('http://www.google.com');
Query OK, 1 row affected (0.00 sec)

index是 MySQL 中的关键字。如果您不使用它作为表名,您的生活会更轻松。但是,如果你真的想要,你可以使用它,但是你必须引用它:

cursor.execute("""INSERT INTO `index`(url) VALUES(%s)""", (url,))

PS:不用打电话

url = mdb.escape_string("http://www.google.com")

当您调用时,MySQLdb 会自动为您执行此操作

cursor.execute("""INSERT INTO index(url) VALUES(%s)""", (url,))

事实上,既然cursor.execute需要mdb.escape_string你,你自己做可能会导致不需要的值被插入到数据库中,具体取决于 的值url

In [105]: MySQLdb.escape_string("That's all folks")
Out[105]: "That\\'s all folks"

In [106]: MySQLdb.escape_string(MySQLdb.escape_string("That's all folks"))
Out[106]: "That\\\\\\'s all folks"
于 2012-10-24T02:08:35.377 回答