首页 > 解决方案 > 将带有 psycopg2 更新命令的 python 输入变量放置到特定列

问题描述

我是 Flask、Psycopg2 和 Python 的初学者,我遇到了这个小问题,我创建了一个 input() 变量来读取用户的答案,我希望将该答案放入我的数据库表的特定列中。

print('Are the eyes Open or Closed?: ')
estate1 = input()

def update_Eyes(self):
update_command = ("UPDATE Eyes SET cstate=%s Where id=1", (estate1,))
self.cursor.execute(update_command)
print("Eye table update successful ")

database_connection = DatabaseConnection()
database_connection.update_Eyes()

如果我尝试自己添加任何值,它工作得很好,但我似乎无法找到添加变量的解决方案。

错误代码如下所示:

Traceback (most recent call last):
File "C:/Users/AJ/Desktop/Data Processing/Flask/first.py", line 136, in <module>
database_connection.update_Eyes()  # Updates Table Eyes
File "C:/Users/AJ/Desktop/Data Processing/Flask/first.py", line 98, in update_Eyes
self.cursor.execute(update_command)
TypeError: argument 1 must be a string or unicode object: got tuple instead

标签: pythonpostgresqlpsycopg2

解决方案


当您将命令编译到其中时update_command,您将其存储为元组:

estate1 = 'test'
update_command = ("UPDATE Eyes SET cstate=%s Where id=1", (estate1,))
print(type(update_command))

<type 'tuple'>

错误是说它需要一个字符串。所以,update_command改为:

update_command = "UPDATE Eyes SET cstate = '{0}' Where id=1".format(estate1)

更改后,您将看到如下内容:

update_command = "UPDATE Eyes SET cstate = '{0}' Where id=1".format(estate1)
print(type(update_command))
<type 'str'>

如果您担心 SQL 注入,可以访问有关如何正确处理用户输入的说明。


推荐阅读