使用python将rss导入MySQL数据库

时间:2015-02-24 00:51:07

标签: python mysql database rss

我尝试使用python将Feed导入{​​{3}}托管的Mysql数据库,但我似乎无法使其正常工作。这是我正在使用的代码。

import MySQLdb
import feedparser

myfeed = feedparser.parse("http://www.couponchief.com/rss/")

for item in myfeed['items']:
        title = item.title
        link = item.link
        description = item.description
        print title
        print link
        print description

        db =                                                  
        MySQLdb.connect('mysql.server','lesmun','*******','lesmun$default');

        with db:

            cur = db.cursor()
            cur.execute("INSERT INTO ini(title, link, description)VALUES(%s,          
            %s, %s)", (title,link,description))
            print 'Succesfull!'


# close the cursor
            cur.close()

# close the connection
        db.close ()

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

可能您使用的是旧版本的MySQLdb,它不支持自动提交事务的上下文管理器。

您可以升级到最新版本make your own,也可以在关闭连接之前显式调用db.commit()

此外,没有必要(或者不希望)为数据库建立新连接,并为插入的每一行创建新游标。你的代码写得更好:

import MySQLdb
import feedparser

myfeed = feedparser.parse("http://www.couponchief.com/rss/")

# get connection and cursor upfront, before entering loop
with MySQLdb.connect('mysql.server','lesmun','*******','lesmun$default') as db:
    cur = db.cursor()

    for item in myfeed['items']:
        title = item.title
        link = item.link
        description = item.description
        print title
        print link
        print description

        cur.execute("INSERT INTO ini (title, link, description) VALUES (%s, %s, %s)", (title, link, description))
        print 'Succesfull!'

#    db.commit()    # for older MySQLdb drivers