为什么MySQL.Connector不起作用,尽管Pymysql正在努力将数据库在本地连接?

问题描述 投票:0回答:1
i尝试使用

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连接器问题的解决方案
python python-3.x database-connection mysql-connector-python
1个回答
0
投票

步长1:修改连接字符串

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
  • 使用其纯Python实现而不是C扩展,绕过任何相关问题。
    有关更多详细信息,请遵循官方MySQL连接器/Python文档:
    MysQL连接器/Python连接参数。
    替代解决方案:安装libmysqlclient

如果您希望使用

libmysqlclient
,请确保安装并可以访问:

下载

libmysqlclient从this this oftical链接

添加了您系统环境变量的库路径。

检查是否已经存在于您的MySQL安装文件夹中。如果确实如此,只需将其位置添加到PATH而不是下载。

这应该有助于解决该问题,同时保持

libmysqlclient
的绩效益处。
	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.