无法从Python访问MySQL数据库

4

我尝试通过Python访问MySQL数据库中的数据,然后我尝试了以下方法:

import MySQLdb

db = MySQLdb.connect(host = "127.0.0.1",
                     port = 3306,
                      user="Bishnu",
                      password = "Pulchowk",
                      db = "telecom_db")
cursor =db.cursor()
cursor.execute("select * from profile")
numrows = int(cursor.rowcount)
for x in range(numrows):
    row = cursor.fetchone()
    #if (row):
    print row[0], row[1]

cursor.close()

db.cose()

然后它会显示错误。

Traceback (most recent call last):
  File "D:\Bishnu\BE\4th year\7th semester\Major Project I\Workspace\Bishnuji\default\first.py", line 43, in <module>
    db = "telecom_db")
  File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
TypeError: 'password' is an invalid keyword argument for this function

然后我还尝试了删除密码

import MySQLdb

db = MySQLdb.connect(host = "127.0.0.1",
                     port = 3306,
                      user="Bishnu",
                      #password = "Pulchowk",
                      db = "telecom_db")
cursor =db.cursor()
cursor.execute("select * from profile")
numrows = int(cursor.rowcount)
for x in range(numrows):
    row = cursor.fetchone()
    #if (row):
    print row[0], row[1]

cursor.close()

db.cose()

仍然显示错误

Traceback (most recent call last):
  File "D:\Bishnu\BE\4th year\7th semester\Major Project I\Workspace\Bishnuji\default\first.py", line 43, in <module>
    db = "telecom_db")
  File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
  File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (1044, "Access denied for user ''@'localhost' to database 'telecom_db'")

可能的解决方案是什么?
3个回答

11

文档上看,正确的参数名称应该是passwd


我把我的密码改成了passwd,但仍然出现了第二种错误,即_mysql_exceptions.OperationalError: (1044, "Access denied for user ''@'localhost' to database 'telecom_db'")。 - Bishnu Bhattarai
用户名在错误信息中缺失,这正常吗?顺便问一下,你确定密码是正确的吗?你能否使用相同的参数从命令行连接? - gipi

2

检查一下你的数据库是否设置了密码。通常情况下,用户名和密码不会被更改,默认用户名为'root',密码为空,即password = ''。如果你已经设置了密码但忘记了它,你可以按照如何检索我的MySQL用户名和密码?所述的说明来检索它。


1
请使用卸载命令卸载mysqlclient,然后重新安装。
pip uninstall mysqlclient

安装

pip install mysqlclient

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