在python中将url添加到mysql行
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在python中将url添加到mysql行,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2192字,纯文字阅读大概需要4分钟。
内容图文
![在python中将url添加到mysql行](/upload/InfoBanner/zyjiaocheng/905/54799ba071c841e99458d4bc5e287965.jpg)
我试图使用python和MySQLdb库在mysql的文本行中添加一个url,但是当我运行我的代码时,它说我的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")
解决方法:
我能够像这样复制你的问题:
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"
内容总结
以上是互联网集市为您收集整理的在python中将url添加到mysql行全部内容,希望文章能够帮你解决在python中将url添加到mysql行所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。