场景:平时直接用root登录到mysql服务器上进行SQL语句查询,当想用python连接mysql时,提示1045, "Access denied for user ‘root‘@‘IP地址‘ (using password: YES)",然后用create user 用户名 identified by ‘密码‘创建了用户名为自己名字的用户,再去执行python,提示1004 Access denied for user ‘用户名‘@‘%‘ to database,这时候就要进入mysql用select * from mysql.user \G查看当前所有用户的情况,会发现别人的权限里很多都是Y,而自己的都是N,所以意识到是权限问题。
解决:给自己的用户名添加权限 grant all privileges on *.* to 用户名@IP地址,然后再select * from mysql.user \G会发现自己的权限也变成了Y,这时候python就能连接数据库了。
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import MySQLdb
conn = MySQLdb.connect(host = "IP地址", user = "用户名", passwd = "密码",
db = "数据库名", port = 3306, charset="utf8")
cur = conn.cursor()
cur.execute("set NAMES UTF8")
if __name__ == ‘__main__‘:
conn.commit()
cur.close()
conn.close()
mysql授权问题:1004 Access denied for user '用户名'@'%' to database