我想查看world用戶輸入的特定 sql 資料庫表的所有資料,下面的代碼將為我提供所需的city表輸出,但我希望用戶輸入表名并想讓我的代碼適用于所有情況.
from sqlite3 import connect
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="",database='world')
mycursor=mydb.cursor()
mycursor.execute("select * from city")
for i in mycursor:
print(i)
我想宣告city為字串變數
table_name=str(input("enter table name:"))
mycursor=mydb.cursor()
mycursor.execute("select * from table_name")
for i in mycursor:
print(i)
但我得到一個錯誤 world.table_name 不存在,我理解。有什么方法可以解決我的問題。尋求幫助,非常感謝。
uj5u.com熱心網友回復:
使用串聯
table_name=str(input("enter table name:"))
query = "SELECT * FROM " table_name
mycursor.execute(query)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486150.html
上一篇:按SQL洗掉分組前的重復項
