Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将python脚本中的数据添加到mysql数据库_Python_Mysql - Fatal编程技术网

将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)

我想知道是否有人能帮我弄清楚为什么我的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)
    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()

请显示“索引”的内容