Using variables within strings for SQL queries using python
P粉195402292
P粉195402292 2024-03-22 12:35:15
0
1
679

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粉195402292
P粉195402292

reply all(1)
P粉495955986

Use concatenation

table_name=str(input("enter table name:"))
query = "SELECT * FROM " + table_name
mycursor.execute(query)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template