Query Current Database Name Using PyMySQL

  • Share this:

Code introduction


This function uses the pymysql library to query the current database name connected to the MySQL database and prints it. If an error occurs during the query, it catches the exception and prints the error message.


Technology Stack : pymysql

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_select_database(cursor):
    from pymysql import err
    try:
        cursor.execute("SELECT DATABASE();")
        database = cursor.fetchone()[0]
        print(f"Currently connected to database: {database}")
    except err.MySQLError as e:
        print(f"An error occurred: {e}")                
              
Tags: