【问题标题】:Unknown column in where clause when updating database更新数据库时 where 子句中的未知列
【发布时间】:2018-04-13 01:48:22
【问题描述】:

我正在尝试将来自两个不同文件的信息添加到记录中,我试图通过打开第一个文件并添加到记录,然后打开第二个文件并更新该记录来实现此目的。

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”只是我的第二个文本文件中第一行的字符串。我现在正在使用字符串格式化程序,否则会出现语法错误,此代码仅用于更新数据库一次,而不是在生产中。

【问题讨论】:

  • 您的for 循环会不断更新表中的相同行并使用不同的回复。这真的是你想要的吗?
  • 不,我不想那样大声笑,我想更新不同的行,这些行具有正确的文本以对应正确的回复。我整天都在为此苦苦挣扎,每条记录是否自动有一个 id 还是你的意思是我应该做一个?

标签: python mysql


【解决方案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)) 

另外,你的循环是错误的。您不想为table2 中的每一行循环遍历整个table3,您只想并行读取这两个文件。见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()

【讨论】:

  • 好的,我不需要在第二个示例中的值周围使用引号吗?
  • 正确,阅读cursor.execute()的文档,看看它是如何进行参数替换的。
  • 好的,谢谢,但这又给我带来了另一个问题。我确实将%s 插入到我的“文本”列下的数据库中
  • text 列正好在WHERE 子句中,这段代码不能修改。它只修改reply 列。
  • 您是否也更改了INSERT 行?如果您摆脱了格式运算符,则必须删除引号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 2020-04-13
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
相关资源
最近更新 更多