kikee1222
kikee1222

Reputation: 2016

Python3 issue with SQL insert

I am running intoan issue with the below. It says

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT\xc2\xa0INTO\xc2\xa0no.top_new VALUES\xc2\xa0(title,\xc2\xa0link,\xc2\xa0description)' at line 1")

I am not sure what is wrong with the query?

 import feedparser, MySQLdb
    db = MySQLdb.connect(host='localhost',user='root',passwd='sdsdf', db='no')
    mycursor = db.cursor()
    d = feedparser.parse('https://news.yahoo.com/rss/entertainment')

    for post in d.entries:
        title = post.title
        link = post.link
        description = post.description
        sql = '''INSERT INTO no.top_new VALUES (title, link, description)'''
        mycursor.execute(sql)

Upvotes: 0

Views: 39

Answers (1)

matwr
matwr

Reputation: 1571

You are not specifying the columns in your INSERT query. This is fine. However, you must ensure that your table has precisely the same number of columns as the inserted values (in your case three) and that the columns in the table structure are in the same order as your INSERT values. Hence, I suspect that your table either has additional columns or is not structured in the order of your given values: tite|link|description.

EDIT

If the structure is correct. Then the issue is likely to be related to the data being inserted, which likely contains invalid characters.

Solution : Rewrite your INSERT query as follows:

sql = "INSERT INTO no.top_new VALUES (%s, %s, %s)"
mycursor .execute(sql, (title, link,description))

This way the string to be inserted will be escaped for you.

Upvotes: 1

Related Questions