1

I am working on a project in Python tkinter for which I have chosen MySQL as my database. i have downloaded MySQL full version so i have tried to connect MySQL using Python mysql.connector

this code the code that i am running:

import mysql.connector

print("Trying...")

try:
    connection = mysql.connector.connect(
        host='127.0.0.1',  # Use this instead of 'localhost'
        user='root',
        password='Admin_123',
        database='testdb'
    )

    if connection.is_connected():
        print("Successfully connected to MySQL.")
        cursor = connection.cursor()

        # Fetch the current database
        cursor.execute("SELECT DATABASE();")
        db_name = cursor.fetchone()
        print(f"Connected to database: {db_name[0]}")

        # Fetch data from the 'users' table
        cursor.execute("SELECT * FROM users;")
        records = cursor.fetchall()

        if records:
            print("Fetching records from 'users' table...")
            for row in records:
                print(row)  # Print each row
        else:
            print("⚠️ No records found in 'users' table.")
    else:
        print("Failed to connect to MySQL.")

except mysql.connector.Error as err:
    print(f"❌ Error: {err}")

finally:
    if 'connection' in locals() and connection.is_connected():
        cursor.close()
        connection.close()
        print("🔌 MySQL connection closed.")

The output I am getting is Trying..., that's all, no error nothing else

  1. I have tried checking if MySQL80 is running.
  2. I run netstat -an | find "3306" to check if MySQL is accepting connections on the expected port.
  3. I even tried changing host='localhost' to host='127.0.0.1'
  4. I have edited my.ini file by adding bind-address=127.0.0.1 under [mysqld] section (all of them are ChatGPT's recommendations)
  5. Even checked the firewall too (chatGPT)

I do not know what the problem is here, the file runs get's this Trying... and runs for 5 sec and exits. The password is right, I have checked that too multiple times.

2
  • 2
    It doesn't sound like it's the case, but are you attempting to access your mysql instance through an SSH tunnel? If so you may need to add use_pure=True to your connection parameters. While I don't see any talk of that parameter helping in cases where a tunnel is NOT being used, it may be worth it to toss that into your connection parameters and see if it gets you through this issue. Commented Apr 30 at 14:22
  • 1
    It works perfectly now! @JNevill Commented Apr 30 at 14:31

0

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.