【发布时间】:2020-04-16 09:09:06
【问题描述】:
我想在 Python 和 Mysql 中使用 Vader 创建情绪分析。问题是,我在mysql上遇到了错误,尤其是在将数据插入数据库时。我得到的错误是 Failed to insert record into MySQL table 1064 (42000): You have an error in your SQL syntax;查看与您的 MariaDB 服务器版本相对应的手册,以在第 2 行的 '['compound'],'negative')' 附近使用正确的语法。代码如下:
sql_select_Query = "select a from table1 union select b from table1"
cursor = connection.cursor()
cursor.execute(sql_select_Query)
records = cursor.fetchall()
for row in records:
print(row)
sid_obj = SentimentIntensityAnalyzer()
sentiment_dict = sid_obj.polarity_scores(row)
if sentiment_dict['compound'] >= 0.05 :
sentiment = 'positive'
elif sentiment_dict['compound'] <= - 0.05 :
sentiment = 'negative'
else :
sentiment = 'neutral'
mySql_insert_query = """INSERT INTO sent (q,polarity,senti) VALUES (%s,%s,%s) """
records_to_insert = [(row,sentiment_dict['compound'], sentiment)]
cursor = connection.cursor()
cursor.executemany(mySql_insert_query, records_to_insert)
connection.commit()
print(cursor.rowcount, "Record inserted successfully into table")
except mysql.connector.Error as error:
print("Failed to insert record into MySQL table {}".format(error))
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
【问题讨论】:
-
在
VALUES (%s,positive')中,positive上缺少一个开放引号,并且只有两个值,但INTO元组需要三个。 -
是的,我已经编辑了代码,但在 'sentiment_dict['compound']' 上仍然出现错误。它无法插入数据库。为什么?