在查询 PyMySQL 中使用 WHERE
Using WHERE in query PyMySQL
我正在尝试创建一个程序,用户可以在其中输入运算符,即 <> 或 =,然后是 pymysql 中数据库的数字。我尝试了多种不同的方法来做到这一点,但不幸的是没有成功。我有两个文档,一个是显示,另一个是将显示导入另一个文档。
文档 1
def get_pop(op, pop):
if (not conn):
connect();
query = "SELECT * FROM city WHERE Population %s %s"
with conn:
cursor = conn.cursor()
cursor.execute(query, (op, pop))
x = cursor.fetchall()
return x
文件二
def city():
op = input("Enter < > or =: ")
population = input("Enter population: ")
pop = display.get_pop(op, population)
for p in pop:
print(pop)
我收到以下错误。
pymysql.err.ProgrammingError:(1064,......
请帮忙谢谢
在检查 op
确实包含“<>”或“=”并且 pop
确实包含一个数字后,您可以尝试:
query = "SELECT * FROM city WHERE Population " + op + " %s";
谨防 SQL 注入。
然后
cursor.execute(query, (pop))
你不能这样做。参数化仅适用于值,不适用于运算符或 table 名称或列名称。您需要将运算符格式化为字符串。 不要将此处的%s
占位符与Python字符串格式混淆; MySQL 很尴尬,因为它使用 %s 作为绑定参数,这与常规 Python 字符串格式冲突。
查询字符串中的 MySQL %s
转义用户输入以防止 SQL 注入。在这种情况下,我设置了一个基本测试,以查看用户提交的操作部分是否在接受的操作列表中。
def get_pop(op, pop):
query = "SELECT * FROM city WHERE Population {} %s" # Add a placeholder for format
with conn: # Where does this come from?
cursor = conn.cursor()
if op in ['=', '!=']:
cursor.execute(query.format(op), (pop,))
x = cursor.fetchall()
return x
在 if op in ['=', '!=']
不是 True
的情况下,您需要提出一些合理的 return
值,但这完全取决于您希望它如何表现。
我正在尝试创建一个程序,用户可以在其中输入运算符,即 <> 或 =,然后是 pymysql 中数据库的数字。我尝试了多种不同的方法来做到这一点,但不幸的是没有成功。我有两个文档,一个是显示,另一个是将显示导入另一个文档。
文档 1
def get_pop(op, pop):
if (not conn):
connect();
query = "SELECT * FROM city WHERE Population %s %s"
with conn:
cursor = conn.cursor()
cursor.execute(query, (op, pop))
x = cursor.fetchall()
return x
文件二
def city():
op = input("Enter < > or =: ")
population = input("Enter population: ")
pop = display.get_pop(op, population)
for p in pop:
print(pop)
我收到以下错误。
pymysql.err.ProgrammingError:(1064,......
请帮忙谢谢
在检查 op
确实包含“<>”或“=”并且 pop
确实包含一个数字后,您可以尝试:
query = "SELECT * FROM city WHERE Population " + op + " %s";
谨防 SQL 注入。
然后
cursor.execute(query, (pop))
你不能这样做。参数化仅适用于值,不适用于运算符或 table 名称或列名称。您需要将运算符格式化为字符串。 不要将此处的%s
占位符与Python字符串格式混淆; MySQL 很尴尬,因为它使用 %s 作为绑定参数,这与常规 Python 字符串格式冲突。
查询字符串中的 MySQL %s
转义用户输入以防止 SQL 注入。在这种情况下,我设置了一个基本测试,以查看用户提交的操作部分是否在接受的操作列表中。
def get_pop(op, pop):
query = "SELECT * FROM city WHERE Population {} %s" # Add a placeholder for format
with conn: # Where does this come from?
cursor = conn.cursor()
if op in ['=', '!=']:
cursor.execute(query.format(op), (pop,))
x = cursor.fetchall()
return x
在 if op in ['=', '!=']
不是 True
的情况下,您需要提出一些合理的 return
值,但这完全取决于您希望它如何表现。