使用psycopg2 update命令将python作为输入变量放置到特定列

2024-05-23 14:34:17 发布

您现在位置: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

Tags: or答案selfflaskinputexecuteupdateconnection
2条回答

将命令编译成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注入,you can visit this explanation of how to handle user input correctly.

这是一个完美的解决方案

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

我只需要在“{0}”周围添加额外的引号,使它能够读取字符串,并且工作得非常好。非常感谢。:)

相关问题 更多 >