0

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
8
  • Your code looks good, and with replacements to my database, I get results with your code copied. The only things I did, not covered by your description, were to launch the DB software, create a test database, add some data to it and close. But that should hardly be necessary. Add logs. It's probably something really minor. Commented Oct 21, 2024 at 19:31
  • Ah hey another thing could be the root user. I created another user and logged in using it in my code. Could there be surprising security settings against using as root? Commented Oct 21, 2024 at 19:36
  • Usually the root user can do anything. What happens if you do this using the regular CLI client? Commented Oct 21, 2024 at 20:22
  • There's no need for if mydb.is_connected(): If it can't connect an exception will be raised. Commented Oct 21, 2024 at 20:23
  • @MikaelM I tried creating a new user, but I'm still facing the same issue. Do you have any additional recommendations I could try? Commented Oct 22, 2024 at 7:55

1 Answer 1

-2

"Record" is a key word in Python referring to a tuple list... "x" doesn't appear to be defined. So the For Loop should read: For record in results:

Then retrieve the "values" for each record

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.