将python脚本中的数据添加到mysql数据库
我想知道是否有人能帮我弄清楚为什么我的python脚本收集的数据没有正确地输入mysql数据库 这是我的密码将python脚本中的数据添加到mysql数据库,python,mysql,Python,Mysql,我想知道是否有人能帮我弄清楚为什么我的python脚本收集的数据没有正确地输入mysql数据库 这是我的密码 /*** index is a dictionary that has the struture: index = {links:[words], links: [words],.......} ***/ #There are multiple items in words for k, v in index.iteritems(): links = str(k)
/*** index is a dictionary that has the struture:
index = {links:[words], links: [words],.......} ***/
#There are multiple items in words
for k, v in index.iteritems():
links = str(k)
words = str(v) [1:-1]
import MySQLdb
db = MySQLdb.connect("localhost","root","","my_db" )
cursor = db.cursor()
try:
cursor.execute(('insert into SITE(url, keywords) values("%s", "%s")' % \
(links,words)))
db.commit()
except:
db.rollback()
db.close()
我的表中的每一行应该有两个字段:url和关键字
它只插入两行,而不是插入6行。
请帮忙 可能有问题,因为您为每个项目打开了一个新连接。然后,您不应该将值格式化为SQL语句,而应该使用参数。第三,您不应该忽略异常,因为这样您就无法找出哪里出了问题。列表的表示形式什么都不是,要在生产代码中使用,请改用join
import logging
import MySQLdb
db = MySQLdb.connect("localhost","root","","my_db" )
for links, words in index.iteritems():
cursor = db.cursor()
try:
cursor.execute('insert into SITE(url, keywords) values(%s, %s)', (links, ','.join(words)))
db.commit()
except Exception:
logging.exception('insert went wrong')
db.rollback()
db.close()
请显示“索引”的内容