如何在python中将字符串值调用到sql查询中
我试图从容器tn(用户提供的输入)调用字符串值来完成sql查询如何在python中将字符串值调用到sql查询中,python,mysql,sql,Python,Mysql,Sql,我试图从容器tn(用户提供的输入)调用字符串值来完成sql查询 # lists is a list in which all table names in the database is stored ct=0 while ct!=2: print("1.Enter the table name you want access") print("2.Exit") ct=int(input("Enter your choice (1 or 2) :")) if ct
# lists is a list in which all table names in the database is stored
ct=0
while ct!=2:
print("1.Enter the table name you want access")
print("2.Exit")
ct=int(input("Enter your choice (1 or 2) :"))
if ct==1:
tn=input("Enter table name :")
break
elif ct==2:
sys.exit(0)
else:
print("INVALID INPUT")
if tn in lists:
print()
print("Table found!")
mycursor.execute("SELECT * FROM (%s)",(tn,))
for i in mycursor:
print(i)
我希望sql查询在执行后变得完整,并向我显示返回的结果(即应该显示用户输入的表)
我在运行代码时收到以下错误消息:-
Traceback (most recent call last):
File "C:\Users\11c1.System2-PC\Desktop\MYSQL\Mysql (Software).py", line 59, in <module>
mycursor.execute("SELECT * FROM (%s)",(tn,))
File "C:\Program Files (x86)\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 551, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Program Files (x86)\Python37-32\lib\site-packages\mysql\connector\connection.py", line 490, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Program Files (x86)\Python37-32\lib\site-packages\mysql\connector\connection.py", line 395, in _handle_result
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''11c')' at line 1
这会产生如下错误:-
Traceback (most recent call last):
File "C:\Users\11c1.System2-PC\Desktop\MYSQL\Mysql (Software).py", line 59, in <module>
mycursor.execute("SELECT * FROM (?)",(tn,))
File "C:\Program Files (x86)\Python37-32\lib\site-packages\mysql\connector\cursor.py", line 543, in execute
"Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
回溯(最近一次呼叫最后一次):
文件“C:\Users\11c1.System2 PC\Desktop\MYSQL\MYSQL(Software.py)”,第59行,在
mycursor.execute(“SELECT*FROM(?),(tn,))
文件“C:\Program Files(x86)\Python37-32\lib\site packages\mysql\connector\cursor.py”,第543行,在execute中
“并非SQL语句中使用了所有参数”)
mysql.connector.errors.ProgrammingError:SQL语句中未使用所有参数
尝试下面的查询syntex:
query= "SELECT * FROM %s"
mycursor.execute(query%(tn,))
希望这有帮助 查询中不需要括号。@skannet,试试
mycursor.execute(query,tn)
@OlvinRoght没有相同的错误mysql.connector.errors.ProgrammingError:1064(42000):您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以获取第行“%s”附近要使用的正确语法1@skannet,在tn
中是什么,只是表的字符串名?@OlvinRoghttn
是用户将输入的表名及其数据类型string@skannet,在函数调用之前,您是否尝试过使用调试器并检查tn
的内容?
query= "SELECT * FROM %s"
mycursor.execute(query%(tn,))