将带有 psycopg2 更新命令的 python 输入变量放置到特定列
Placing a python an input variable with a psycopg2 update command to a specific column
我是 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
当您将命令编译成 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}”周围添加额外的引号,使其能够读取字符串并且它工作得非常好。太感谢了。 :)
我是 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
当您将命令编译成 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}”周围添加额外的引号,使其能够读取字符串并且它工作得非常好。太感谢了。 :)