python版本为3.5,mysql版本为5.7.21,
create database: py4e
create table: PymySqlTest,
安装pymysql
pip3 install pymysql
提示
Requirement already satisfied: pymysql in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
在pycharm项目里通过 Preference-> 我的project -> ..Intepreter 安装 pymysql
在mysqldb创建table,开启权限
GRANT ALL PRIVILEGES ON PY4E.* TO 'root'@'localhost' IDENTIFIED BY 'pswd' WITH GRANT OPTION;
SHOW GRANTS FOR 'root'@'localhost';
FLUSH PRIVILEGES;
在Pycharm中测试
#!/usr/bin/env python3
# GRANT ALL PRIVILEGES ON tablename.* TO 'root'@'localhost' IDENTIFIED BY 'root' WITH GRANT OPTION;
# FLUSH PRIVILEGES;
import pymysql
# Connect to the database
connection = pymysql.connect(host='127.0.0.1',
user='root',
password='root',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
Hover on 执行文件 pymysql 没有提示出错
执行文件提示错误:
pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)")
求解?
既然:
设置
password
为pswd
那么:
这里的
password
就应该是pswd
, 而不是root
.