简体   繁体   English

将数据从python脚本添加到mysql数据库

[英]Adding data from python script into mysql database

I was wondering if anyone could help me figure out why the data that my python script has gathered is not being input into the mysql database properly 我想知道是否有人可以帮助我找出为什么我的python脚本收集的数据没有正确输入到mysql数据库中

Here is my code 这是我的代码

/*** 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()

Each row in my table should have two feilds: url and keywords Instead of insterting 6 rows it only inserts two. 表中的每一行应具有两个字段:url和关键字,而不是插入6行,而仅插入两行。 Please help?! 请帮忙?!

Perhaps there is a problem, because you open a new connection for every item. 也许有问题,因为您为每个项目打开了一个新连接。 Then you shouldn't format values into a SQL-statement, use parameters instead. 然后,您不应该将值格式化为SQL语句,而应使用参数。 Third, you shouldn't ignore exceptions, because then, you cannot figure out, what's going wrong. 第三,您不应该忽略异常,因为那样您就无法弄清楚到底出了什么问题。 The representation of a list is nothing, to work with in production code, use join instead 列表的表示没什么,要在生产代码中使用,请改用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM