Created
December 9, 2023 01:02
-
-
Save algonacci/33448947c571bed2a53bf997ec532939 to your computer and use it in GitHub Desktop.
Check MySQL Database Connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql.connector | |
def check_tables_in_database(host, username, password, database): | |
try: | |
# Attempt to connect to the MySQL database | |
connection = mysql.connector.connect( | |
host=host, | |
user=username, | |
password=password, | |
database=database | |
) | |
if connection.is_connected(): | |
print(f"Connected to the MySQL database: {database}") | |
# Create a cursor to execute SQL queries | |
cursor = connection.cursor() | |
# Retrieve the list of tables in the database | |
cursor.execute("SHOW TABLES") | |
# Fetch and print the table names | |
tables = cursor.fetchall() | |
if tables: | |
print("Tables in the database:") | |
for table in tables: | |
print(table[0]) | |
# Close the cursor and connection | |
cursor.close() | |
connection.close() | |
except mysql.connector.Error as e: | |
# If there's an error, print an error message | |
print(f"Error connecting to the database: {str(e)}") | |
if __name__ == "__main__": | |
# Replace with your MySQL database connection details | |
host = '' | |
username = '' | |
password = '' | |
database = '' | |
check_tables_in_database(host, username, password, database) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment