1

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.

1 Answer 1

1

Use concatenation

table_name=str(input("enter table name:"))
query = "SELECT * FROM " + table_name
mycursor.execute(query)
Sign up to request clarification or add additional context in comments.

2 Comments

Someone had to add this.. Use prepared statements.
Or at least, quote the table name with backticks: q = 'select * from `%s` % table_name to reduce the risk of SQL injection (checking that the table name is an actual table would also be wise).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.