简体   繁体   中英

Unable to insert data to MySQL with Python/MySQL Connector

I'm new to Python (learnt how to code with it in 2 days ago). I'm trying to get feeds from MySQL database and insert theme into other table. But nothing inserted.

Here is my code:

    cnx = MySQLConnection(**db_config)
    if cnx.is_connected():
        print("Database connected successfully...")

    cursor = cnx.cursor(dictionary=True)
    cursor.execute("SELECT * from external_feeds WHERE discipline = 'ALL' AND actif = 1")

    rows = cursor.fetchall()

    insert_feed = ("INSERT INTO feeds "
    "(categorie, urlflux, titreflux, photonews, textnews, date, titrenews, liensnews, slug, photo)"
    "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")


    for row in rows:
        feed = feedparser.parse(row["url"])
        feed_link = row["url"]
        name = row["name"]
        image = row["photo"]
        category = row["discipline"]

        x = len(feed.entries)
        for i in range(x):
            feed_title = feed.entries[i].title
            print feed_title
            feed_url = feed.entries[i].link
            print feed_url
            feed_published = feed.entries[i].published
            dPubPretty = strftime(feed_published, gmtime())
            feed_description = feed.entries[i].description
            slug = re.sub('[^a-zA-Z0-9 \n\-]', '', feed_url)
            slug = slug.replace('httpwww', '')
            slug = slug.replace('http', '')
            # print insert_feed
            data_feed = (category, feed_link, name, None, feed_description, dPubPretty, feed_title, feed_url, slug, image)
            try:
                cursor.execute(insert_feed, data_feed)
                cursor.commit()
            except:
                cnx.rollback()
                cursor.close()

Is there anyone who can help me figure out where the problem is? I am completly new to this so I'm totally lost

I see that you are performing 'cursor.commit()' after inserting the data, which is incorrect, try using 'cnx.commit()'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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