mysql.connector从python脚本连接我的mysql数据库,但无法连接。然后,我尝试使用Pymysql进行连接,并成功连接了DB。为什么我无法使用MySQL连接器连接,即使我可以使用pymysql?连接?
i在VS代码编辑上写下了以下代码,文件名是dbconnector.py
import mysql.connector
from mysql.connector import Error
try:
print("Trying to connect to the database...")
mydb = mysql.connector.connect(
host="127.0.0.1",
user="root",
password="s12345678"
)
if mydb.is_connected():
print("Database connected successfully")
else:
print("Failed to connect to the database")
except Error as e:
print(f"Error: {e}")
然后我检查并发现服务器正在运行,用户和密码正确。然后,我使用cryptography
安装
pip install cryptography
。我的Python版本是
3.12.6
,MysqlServer版本是
8.0.39
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 's12345678' WITH GRANT OPTION;
FLUSH PRIVILEGES;
mysqlConnector官方文档,这是可以的。
我通过运行授予所有许可:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 's12345678';
FLUSH PRIVILEGES;
然后我更改了root的身份验证模式:
netstat -an | findstr "3306"
我确保MySQL通过运行在正确的端口上运行:
use_pure=True
Python的MySQL连接器问题的解决方案
trory将
import mysql.connector
conn = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database",
use_pure=True
)
添加到您的mysql连接字符串:
libmysqlclient
如果这解决了问题,请继续阅读以解释。
为什么这起作用?toby默认,MYSQL连接器/Python
试图使用C扩展
libmysqlclient
以提高性能。但是,在某些情况下,尤其是在某些平台或特定的Python环境上 - C扩展可能无法正常工作:
缺少或不兼容的Python version compatibility
库。
与platform-specific
或
use_pure=True
约束有关的评估。
C extension
部队有关更多详细信息,请遵循官方MySQL连接器/Python文档:MysQL连接器/Python连接参数。 替代解决方案:安装libmysqlclient
如果您希望使用
libmysqlclient
,请确保安装并可以访问:
下载libmysqlclient
从this this oftical链接。
检查是否已经存在于您的MySQL安装文件夹中。如果确实如此,只需将其位置添加到PATH
而不是下载。
这应该有助于解决该问题,同时保持
libmysqlclient
的绩效益处。