我正在尝试将信息添加到来自两个不同文件的记录中,我试图通过打开第一个文件并添加到记录,然后打开第二个文件并更新该记录来实现此目的。
with open('C:/Users/ELITEBOOK/documents/github/chatbot/chatbot/bot/human_text.txt', 'r') as table2, open('C:/Users/ELITEBOOK/documents/github/chatbot/chatbot/bot/robo_text.txt','r') as table3:
for line in table2.readlines():
message_text = line
#for robo_line in table3.readlines():
message_intent = ''
message_entities = ''
test = 'hello'
#cursor.execute('START TRANSACTION')
cursor.execute("INSERT INTO conversation (text) VALUES ('%s')" % line)
cnx.commit()
#cursor.execute((line))
for robo_line in table3.readlines():
#message_reply = robo_line
cursor.execute("UPDATE conversation SET reply = '%s' WHERE text = %s " % (robo_line, line))
#cursor.execute(robo_line)
cnx.commit()
我收到Unknown column 'start' in 'where clause'
错误,“start”只是我第二个文本文件中第一行的字符串。有帮助吗?我现在正在使用字符串格式化程序,因为否则我会收到语法错误,此代码仅用于更新数据库一次,而不是生产中。
答案 0 :(得分:1)
您需要在值周围加上引号,因为它是一个字符串,就像您为要设置reply
的字符串所做的那样。
cursor.execute("UPDATE conversation SET reply = '%s' WHERE text = '%s' " % (robo_line, line))
但最好使用预准备语句而不是字符串格式,以防止SQL注入。然后你不要在占位符周围加上引号,cursor.execute
安全地替换它们。
cursor.execute("UPDATE conversation SET reply = %s WHERE text = %s ", (robo_line, line))
此外,您的循环错误。您不想遍历table3
中每一行的整个table2
,您只想并行读取这两个文件。见Read two textfile line by line simultaneously -python
with open('C:/Users/ELITEBOOK/documents/github/chatbot/chatbot/bot/human_text.txt', 'r') as table2, open('C:/Users/ELITEBOOK/documents/github/chatbot/chatbot/bot/robo_text.txt','r') as table3:
for line, robo_line in zip(table2, table3):
message_text = line
message_intent = ''
message_entities = ''
test = 'hello'
#cursor.execute('START TRANSACTION')
cursor.execute("INSERT INTO conversation (text, reply) VALUES (%s, %s)", (line, robo_line))
cnx.commit()