pythonmysqlmysql-connector-python

How to fix "AttributeError: 'module' object has no attribute 'connect'" with Python mysql connector?


How to solve the issue where my code can't connect to the MySQL database?

import mysql, time

def login():
    db = mysql.connect(host='localhost',user='pi',password='1234',db='mydb')
    cursor = db.cursor()

    while True:
        usercode = input("Please enter your usercode: ")
        password = input("Please enter your password: ")

        sql = "SELECT * FROM `data` WHERE usercode = %s AND password = %s"
        curosr.execute(sql,(usercode,password))
        results = cursor.fetchall()

        if results:
                print("SUCCESS")
                break

        else:
            print("Usercode and password not recognised")
            again = input("Please press any number if you want to try again or * if you want to exit")
            if again.lower() == "n":
                print("Goodbye")
                time.sleep(1)
                break
login()

This is the error that I get on the command line:

 pi@raspberrypi:~ $ python T1.py
Traceback (most recent call last):
  File "T1.py", line 26, in <module>
    login()
  File "T1.py", line 4, in login
    db = mysql.connect(host='localhost',user='pi',password='1234',db='mydb')
AttributeError: 'module' object has no attribute 'connect'

Solution

  • import mysql.connector
    conn = mysql.connector.connect(host='localhost',user='pi',password='1234',db='mydb')