Python | MySQL | 属性错误:模块“mysql.connector”没有“connect”属性。

4

我正在学习Python中的一个新库mysql。我尝试执行以下命令:

import mysql.connector

mydb= mysql.connector.connect(
            host= 'localhost',
            user= 'root',
            passwd= 'skviknesh'
            )
print(mydb)

并且得到了以下错误!
Traceback (most recent call last):

  File "<ipython-input-1-f9b9bc67dd68>", line 3, in <module>
    mydb= mysql.connector.connect(

AttributeError: module 'mysql.connector' has no attribute 'connect'

我查看了类似的其他Stack Overflow问题......没有得到解决方案。我还尝试过重命名文件,但那也没用。请在这个问题上帮忙!

您在连接字符串中没有指定DB值,我认为您需要使用查询来获取在此处打印的有用值。请参阅:https://www.a2hosting.co.uk/kb/developer-corner/mysql/connecting-to-mysql-using-python - C-Sway
1
您的代码片段与您的错误不匹配。在错误片段中,您正在尝试导入“mysql.connector.connect”,而不是“mysql.connector”。我可以友善地建议您完成整个官方Python教程吗?这肯定会为您节省大量时间、痛苦和挫折... - bruno desthuilliers
@brunodesthuilliers 谢谢你的热心建议。我已经编辑了问题中的错误部分。请现在检查一下。 - Viknesh S K
@C-Sway 谢谢!我希望这个方法可以在没有数据库值的情况下工作,因为我正在尝试使用Python和Mysql库在新的服务器连接中创建一个数据库和表。另外,在你分享的链接中,他们使用了import MySQLdb,而我正在尝试使用import mysql.connector - Viknesh S K
3个回答

9

当我遇到了同样的问题时,我只需使用pip uninstall mysql-connector-python卸载该软件包,并使用pip install mysql-connector-python重新安装即可,然后它就可以正常工作:D


2
通常发生这种情况是因为您安装了错误的软件包。 可能在安装过程中,您使用了以下pip命令: pip install mysql-connector 但实际上您需要安装以下软件包: pip install mysql-connector-python 像这样:
C:\Users\tuhin Mitra>pip install mysql-connector-python
Requirement already satisfied: mysql-connector-python in c:\users\tuhin mitra\appdata\local\programs\python\python37-32\lib\site-packages (8.0.19)
Requirement already satisfied: protobuf==3.6.1 in c:\users\tuhin mitra\appdata\local\programs\python\python37-32\lib\site-packages (from mysql-connector-python) (3.6.1)
Requirement already satisfied: dnspython==1.16.0 in c:\users\tuhin mitra\appdata\local\programs\python\python37-32\lib\site-packages (from mysql-connector-python) (1.16.0)
Requirement already satisfied: setuptools in c:\users\tuhin mitra\appdata\local\programs\python\python37-32\lib\site-packages (from protobuf==3.6.1->mysql-connector-python) (45.1.0)
Requirement already satisfied: six>=1.9 in c:\users\tuhin mitra\appdata\roaming\python\python37\site-packages (from protobuf==3.6.1->mysql-connector-python) (1.12.0)

0
我在尝试从Python连接到MySQL时也遇到了同样的问题,我已经纠正了以下问题,你可能有以下其中一个问题:
  1. 使用适当的库安装
  2. 使用确切的密码类型与数据库连接(因为默认情况下MySQL使用caching_sha2_password)。你必须显式地传递密码类型。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接