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.
asked Jun 5, 2022 at 19:41
def __init__
1,0662 gold badges9 silver badges24 bronze badges
1 Answer 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
rici
Someone had to add this.. Use prepared statements.
snakecharmerb
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).default