PyMySQL 是python 3.X 版本中用于连接 MySQL 服务器的一个库,python 2.X则使用MySQLdb
安装PyMySQL:
pip install PyMySQL
或者
pip3 install pymysql
使用方法:
# -*-encoding:utf-8 -*-
import pymysql
conn = pymysql.connect(host='192.168.XX.XX',user='root', password='xxxxxx', database='xxxxx', charset='utf8')
cursor = conn.cursor()
query = ('select a1,a2 from a_test')
cursor.execute(query)
for (a1,a2) in cursor:
print(a1,a2)
cursor.close()
conn.close()
如果提示 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
则在dos命令行输入如下命令,更改mysql连接方式:
mysql -u root -p+mysql密码
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysql密码';
更改完毕后,重新再执行。