How do I connect to MySQL without using a password? (PyMySQL)

Viewed 3323

Here's the relevant part of my code:

        try:
            if self.pass_entry.get():
                self.connection = pymysql.connect(
                    host=self.host_entry.get(),
                    user=self.user_entry.get(),
                    password=self.pass_entry.get(),
                    db=self.db_entry.get(),
                    charset="utf8mb4",
                    cursorclass=pymysql.cursors.DictCursor
                )
            else:
                self.connection = pymysql.connect(
                    host=self.host_entry.get(),
                    user=self.user_entry.get(),
                    db=self.db_entry.get(),
                    charset="utf8mb4",
                    cursorclass=pymysql.cursors.DictCursor
                )
        except Exception as e:
            self.console.insert(tk.END, "Error: {err}\n".format(err=str(e)))

Here's the error:

Connecting to 127.0.0.1...
Error: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")

There's no password on "root" here, and PyMySQL is supposing that it has one. How can I connect without using a password? (I've tried to omit the password option when the password field / string is empty, but PyMySQL doesn't take it into account).

2 Answers

When there is no password for the database you need to pass "" to the function as password.

Try this in your else:

        else:
            self.connection = pymysql.connect(
                host=self.host_entry.get(),
                user=self.user_entry.get(),
                password="",
                db=self.db_entry.get(),
                charset="utf8mb4",
                cursorclass=pymysql.cursors.DictCursor
            )

I had the same problem while using mysql.connector library. Got around it by simply creating a new connection-user in addition to root.

After googling for a while it seemed like the access to root could be the problem, but I dropped looking further into it after I found the mentioned solution. The user has the same settings in MySQL as root@localhost.

def mySQLcnx(someVariable):
        dbCnx = mysql.connector.connect(host="localhost", user="pythonCnx", database="someDatabase")
        dbCnxCursor = dbCnx.cursor()
        dbCnxCursor.execute(someStatement)
        DbQueryResults = dbCnxCursor.fetchall()
Related