mysql.connector.errors.ProgrammingError: 1064 (4200): 你的 SQL 语法有错误;

Ste*_*eve 6 python mysql

我正在尝试将数据插入 MySQL 数据库。我正在使用 python 2.7,我正在使用 mysql.connector。

我的错误是:

mysql.connector.errors.ProgrammingError: 1064 (4200): 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在第 1 行的 '%s) 附近使用的正确语法。

这表明我的代码中有错误,我试图插入我的变量 np (VALUES (%s)");)。np 是一个“名词短语”,例如“滑板”。

import mysql.connector
from textblob import TextBlob

cnx = mysql.connector.connect(user='XXX', password='XXX',
                              host='XXXXX',
                              database='XXXX')

cursor = cnx.cursor(buffered=True)

Latest = ("SELECT * FROM SentAnalysis")
cursor.execute(Latest)

for row in cursor.fetchall():
    SentText = row[2]
    blob = TextBlob(SentText)
    for np in blob.noun_phrases:
        print(np)
        SQLInsertCmd = ("INSERT INTO TestNounPhrase (NPhrase) VALUES (%s)")
        cursor.execute(SQLInsertCmd,np)

cnx.commit()
cursor.close()
cnx.close()
Run Code Online (Sandbox Code Playgroud)

手册中的示例是https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-transaction.html。例如

 "VALUES (%s, %s, %s, %s, %s)")
Run Code Online (Sandbox Code Playgroud)

我看不出有什么不同。此处也详细讨论了此错误:如何修复 MySQL 错误 #1064?stackoverflow 上的其他类似示例都与保留字冗余逗号相关联。但是看着这些示例,我无法发现明显的错误。

任何关于我哪里出错的建议将不胜感激。

abh*_*mar 6

我认为这里的问题可能是查询末尾的分号。

祝你有美好的一天。


Vik*_*kov 6

SQL 查询中的 str 参数必须在引号 'str' 中。
因此,需要使用 '%s' 和 ' ' 来表示 str,而 %s 不带 ' ' 来表示数字:

cursor.execute("""INSERT INTO db_name (str,int,str,int)
                  VALUES ('%s', %s, '%s', %s)""" % (str,int,str,int))
cnx.commit()
Run Code Online (Sandbox Code Playgroud)


pri*_*esh 2

尝试这个

SQLInsertCmd = """INSERT INTO
                  TestNounPhrase (NPhrase) VALUES ((%s))"""  % (np)
cursor.execute(SQLInsertCmd)
Run Code Online (Sandbox Code Playgroud)