在 python 中使用 pymysql 连接数据库

connecting database using pymysql in python

我仍在学习如何使用 python 库来处理数据库

执行以下代码时出现操作错误 screenshot

代码片段:

import pymysql
db1=pymysql.connect(host="127.0.0.1",user="root",password='root',port=3306,db='world')

a=db1.cursor()

sql='SELECT * from CITY'
print(a.execute(sql))

错误:

(1045, "Access denied for user 'root'@'localhost' (using password: NO)")

这可能是什么原因?

An operational error has occurred while executing the following code screenshot. what could be the reason for this?

  • 问题中的错误是:

    (1045, "Access denied for user 'root'@'localhost' (using password: NO)")
    

    这表明您在尝试不使用密码进行连接,而您实际上在连接参数中提供了密码。这曾经是 pymysql 的已知错误,因此答案可能取决于版本。如果您通常可以使用 mysql -u root -proot world(连接参数中的数据库、密码和用户)连接到 mysql,这意味着您的数据库确实具有正确的凭据并且需要密码,而连接方法未发送密码,大多数情况下可能是由于旧版本。另一方面,如果您无法连接,则很可能您的 root 密码为空,您需要正确设置它。还有一个选项是您在访问 root 用户的数据库 'world' 时遇到问题。