gpt4 book ai didi

python - python 中的编程错误,如何使用 SQL 查询解析表中元组的值?

转载 作者:太空宇宙 更新时间:2023-11-03 12:03:19 25 4
gpt4 key购买 nike

为了分别解析表admin_details的用户名和密码字段中变量a和b的值,我尝试了这种方法,伪代码如下:

...
...
a=4
b=8
....
....
cur.execute("INSERT INTO admin_details(username, password) VALUES('%s','%s'), %(a,b)")
....

我在表中插入的值是
username: 4
password:8

但是为了插入像**
a='john'
b='snow'
这样的字符admin_details 字段。我尝试如下使用元组

a='john'
b='snow'
tup=['a','b']

为了将元组的值 a 和 b 插入表中,我尝试了所有可能的方法,但仍然无法将变量存储在表中。

cur.execute("INSERT INTO admin_details(username, password)  VALUES('%s','%s'), % ['a','b']")

但是我明白了

_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INTO INTO admin_details(username) VALUES('%s'), %('entry1.get()')' at line 1")

最佳答案

不要尝试使用字符串格式来构造 SQL 查询。将第二个参数中的查询参数传递给 execute() - 这样您就可以保护自己免受 sql injection 的侵害问题:

a = 'john'
b = 'snow'
cur.execute("INSERT INTO admin_details(username, password) VALUES(%s, %s)", (a, b))

请注意,在这种情况下,您也不需要在查询中的占位符周围加上引号。

另见:

关于python - python 中的编程错误,如何使用 SQL 查询解析表中元组的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27874170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com