【发布时间】:2018-11-11 00:16:20
【问题描述】:
我的问题涉及在下面的cursor.execute 中传递一个字符串
import pymsyql
import json
connection = pymysql.connect(
host='localhost', user='u_u_u_u_u',
password='passwd', db='test',
charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor
)
def get_data(table):
try:
with connection.cursor() as cursor:
sql = """
SELECT * FROM %s;
"""
cursor.execute(sql, (table,))
result = cursor.fetchall()
return json.dumps([dict(ix) for ix in result])
except (TypeError, pymysql.err.ProgrammingError) as error:
print(error)
finally:
pass
get_data('table_1')
connection.close()
我得到了错误
pymysql.err.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 ''table_1'' at line 1")
似乎execute 不希望将字符串作为参数传递;当我直接输入一个字符串时,比如cursor.execute(sql, ('table_1',)),我得到了同样的错误。
我对导致问题的原因感到困惑,双引号 ''table_1'' 令人困惑。谁能告诉我这里发生了什么?
【问题讨论】:
-
很遗憾,您不能以这种方式指定表名。您必须将表名
format()输入到查询中,并且您有责任对其进行清理。