How to change or fill database name inside variable

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)


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

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__":

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x