简体   繁体   中英

Python: error connecting to mysql server using socket

I'm tring to connect to my local mysqlserver.

The following code works on another machine:

root@host> mysql  --protocol=SOCKET
MariaDB [(none)]>

root@host> ls -la /var/run/mysqld/mysqld.sock 
srwxrwxrwx 1 mysql mysql 0 Jun  9 20:27 /var/run/mysqld/mysqld.sock

root@host> python3
>>> import mysql.connector
>>> mysql.connector.connect( unix_socket='/var/run/mysqld/mysqld.sock' )

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/mysql/connector/__init__.py", line 173, in connect
    return MySQLConnection(*args, **kwargs)
File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 102, in __init__
    self.connect(**kwargs)
File "/usr/lib/python3/dist-packages/mysql/connector/abstracts.py", line 735, in connect
    self._open_connection()
File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 250, in _open_connection
    self._do_auth(self._user, self._password,
File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 172, in _do_auth
    self._auth_switch_request(username, password)
File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 216, in _auth_switch_request
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1698 (28000): Access denied for user ''@'localhost'

What may be the root of the problem?

Note that

  • I want to use a Socket and not TCP for reasons.
  • I don't want to use username/password.
  • This works on my other host but I can't figure out why it wont work on this one.

what I suggest first of all is to use a GUI tools like MYSQL workbench or Dbeaver to connect to your database, if it's established you can use this script to connect to your database:

from getpass import getpass
from mysql.connector import connect, Error

try:
    with connect(
        host="localhost",
        user=input("Enter username: "),
        password=getpass("Enter password: "),
    ) as connection:
        print(connection)
except Error as e:
    print(e)

I hope that these can help you to resolve your issue.

If you want to use mysql with socket you can use this method:

import MySQLdb
db = MySQLdb.connect("localhost", "root", "l542212h", "TESTDB", charset='utf8' ,unix_socket="/tmp/mysql.sock")

I hope that can help you to resolve your issue.

You need to specify the user, and clear the password; eg

mysql.connector.connect(unix_socket='/run/mysqld/mysqld.sock', user='root', password=None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM