【问题标题】:Adding data from python script into mysql database将python脚本中的数据添加到mysql数据库中
【发布时间】:2014-11-09 18:52:09
【问题描述】:

我想知道是否有人可以帮助我弄清楚为什么我的 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 行。 请帮忙?!

【问题讨论】:

  • 请显示“索引”的内容

标签: python mysql


【解决方案1】:

也许有问题,因为您为每个项目打开了一个新连接。那么您不应该将值格式化为 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 2017-02-07
    • 2014-05-26
    • 2017-07-14
    • 1970-01-01
    相关资源
    最近更新 更多