Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a variable inside the string for SQL queries using python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use concatenation

table_name=str(input("enter table name:"))
query = "SELECT * FROM " + table_name
mycursor.execute(query)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading