In my code below I want to fill database name using input to choose one of existing databases
import mysql.connector
mydb = mysql.connector.connect(host = 'localhost', port = '3306', user = 'root', password = '',
database = user_input )
mycursor = mydb.cursor()
def choosedb():
user_input = input("choose database name : ")
mycursor.execute('Show tables')
for tb in mycursor:
print (tb)
choosedb()
CodePudding user response:
From what I have understood, you need to ask user to input the db you want to list tables from. You have already written most of the code, so here is a little improvement to your code.
from mysql import connector
mydb = connector.connect(host="localhost", user="root", password="")
mycursor = mydb.cursor()
def get_input():
# this function will keep on asking for input if the user gives in empty field
x = input("Database name: ")
if not x == "":
return x
get_input()
def choosedb():
# using while loop is optional if you just want to run script once.
while True:
# you get user input here as x
x = get_input()
# then query on the db server
mycursor.execute(f"SHOW FULL TABLES FROM {x};")
for table in mycursor:
# then all tables are listed with table name and type and separated by TAB
print(*table, sep="\t")
if __name__ == "__main__":
choosedb()