我正在编写一个模块,以便以更聪明的方式(根据我的需要)在 Python 中使用 connector
,但我遇到了 self.__cursor 引发的错误。执行(查询,values_escaped)
。
代码如下:
class MySQL:
# [...]
def query(self, query: str, values_escaped: tuple = ()) -> MySQLCursorPrepared | MySQLCursorBuffered:
# [...] <-- Here I don't change any parameter of the ones up, they stay untouched until reaching the bugged row below
try:
if values_escaped:
self.__cursor = self.__conn.cursor(prepared = True)
self.__cursor.execute(query, values_escaped) # <-- this is the bugged row
else:
self.__cursor = self.__conn.cursor(buffered = True)
self.__cursor.execute(query)
# [...]
# [...]
def test() -> None:
with MySQL(database = "lockfile") as conn:
res = conn.query("SELECT * FROM %s", ("fileslocked",)) # <-- I can't see any '?' sign! :(
print(f"Rows: {res.rowcount}")
# Output:
Traceback (most recent call last):
File "e:\xampp\htdocs\it-exercises\python\mylockfile\database.py", line 61, in query
self.__cursor.execute(query, values_escaped)
File "E:\Apps\Python310\lib\site-packages\mysql\connector\cursor_cext.py", line 1031, in execute
self._stmt = self._cnx.cmd_stmt_prepare(operation)
File "E:\Apps\Python310\lib\site-packages\mysql\connector\connection_cext.py", line 517, in cmd_stmt_prepare
raise InterfaceError(str(err)) from err
mysql.connector.errors.InterfaceError: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1
Rows: 0
我在网上搜索,但只找到了这个解决方案:光标方法中的 prepared
参数。我在一些非官方的docs中找到的的 connector
而在官方中我找不到任何有用的东西(我可能留下了一些东西,但我已经为此苦苦挣扎了几天),但它似乎不起作用.
此外,“?”在哪里?标志从何而来?
最佳答案
?
表示查询中的占位符,在 Python 中用 %s
表示。
问题是您正在尝试动态绑定(bind)表名,这是不可能的 - 占位符只能动态绑定(bind)到值,而不是对象名称。删除占位符就可以了:
res = conn.query("SELECT * FROM fileslocked")
关于python - MySQL 查询 : check the syntax near '?' . 中的语法错误 '?' 来自哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73347244/