i want to see all the data of a particular table of sql database world
entered by user, The below code will give me desired output for city
table, but i want table name to be entered by user and wants to make my code work for all the cases.
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 thought to declare city
as 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'm getting an error world.table_name doesn't exist, which i understand. is there any way to evolve at solution of my case. looking for kind help, thanks a lot.
CodePudding user response:
Use concatenation
table_name=str(input("enter table name:"))
query = "SELECT * FROM " table_name
mycursor.execute(query)