python - 将带有 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
解决方案
当您将命令编译到其中时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 注入,可以访问有关如何正确处理用户输入的说明。
推荐阅读
- sql - JPA EntityGraph 使用子图制作笛卡尔积
- c# - 使用 Linq 和 Regex 比较 2 个字符串数组以进行部分匹配
- sql-server - SQL 中的 STUFF(... FOR XML) 函数有没有办法防止重复值?
- string - 如何将单词列表读入包含单词位置的元组?
- flutter - 错误:参数类型“列表”
'不能分配给参数类型'String' - kotlin - 从普通列表构建链接列表
- mysql - 一次获取所有数据 - 使用 MySQL 和 SWI Prolog 在 odbc 查询中选择字符串
- python - 我的usb加密解密程序中的cryptography.fernet.InvalidToken
- bash - 循环中的计时器 - Bash
- javascript - 过滤和连接对象数组javascript