I want to view all the data of a specific table of the sql database world
entered by the user, the following code will give me the desired output for the city
table, but I want the table name Entered by the user and want to make my code work for all situations.
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)
I want to declare city
as a string variable
table_name=str(input("enter table name:")) mycursor=mydb.cursor() mycursor.execute("select * from table_name") for i in mycursor: print(i)
But I get the error world.table_name does not exist, I understand. Is there any solution to my situation? Looking for kind help, thank you very much.
P粉4959559862024-03-23 10:48:00
Use concatenation
table_name=str(input("enter table name:")) query = "SELECT * FROM " + table_name mycursor.execute(query)