No Output When Connecting MySQL with Python
I am trying to connect MySQL with Python. When I run my code, I see no output, even though I expect to see a list of databases. Here’s my code:
import mysql.connector
try:
mydb = mysql.connector.connect(host="localhost", user="root", password="mysql1234")
if mydb.is_connected():
print("Connection successful")
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
results = mycursor.fetchall() # Fetch data
if results:
for x in results:
print(x)
else:
print("No databases found.")
else:
print("Connection failed.")
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
if 'mydb' in locals() and mydb.is_connected():
mycursor.close()
mydb.close()
Issue:
- I can connect to the server, but I don't see any databases listed. What might be wrong?
Environment:
- Python version: 3.11
- MySQL version:8.0.15
- Operating System: Windows
if mydb.is_connected():If it can't connect an exception will be raised.