我已经使用 Python 脚本几年了,在 Xubuntu 20.04 上没有出现任何问题,现在在 24.04 上,我在连接到同一台计算机上的 MySQL 服务器时遇到错误。
相关代码:
import requests
import datetime
import json
from urllib.parse import urlencode, quote_plus
from time import sleep
import mysql.connector
def connectDB():
return mysql.connector.connect(
host="localhost",
user="myuser",
passwd="mypass",
database="HomeManagement",
auth_plugin='mysql_native_password'
)
timeNow = datetime.datetime.now().replace(microsecond=0, second=0)
print(timeNow)
mydb = connectDB()
错误:
2024-05-18 19:32:00 Traceback (most recent call last): File "/usr/local/bin/test.py", line 19, in <module> mydb = connectDB() ^^^^^^^^^^^ File "/usr/local/bin/test.py", line 9, in connectDB return mysql.connector.connect( ^^^^^^^^^^^^^^^^^^^^^^^^ 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 155, in _do_auth self._socket.switch_to_ssl(ssl_options.get('ca'), File "/usr/lib/python3/dist-packages/mysql/connector/network.py", line 427, in switch_to_ssl self.sock = ssl.wrap_socket( ^^^^^^^^^^^^^^^ AttributeError: module 'ssl' has no attribute 'wrap_socket'
四处搜索,似乎是因为 python 3.12 中发生了一些变化,但我不能完全确定它。
尝试过使用 pymsql 但得到:
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)")
我在 Python 3.12 、 xampp (php 7.3) 中遇到了同样的问题 然后我执行“pip uninstall mysql-connector-python”
然后再次安装“pip install mysql-connector-python==8.0.21”
现在工作正常。 笔记:: 直接 pip install mysql-connector-python 安装的是大约 9 版本,所以它不起作用,这就是为什么我卸载 9 并安装 8.0.21 版本。