一.Python操作MySQL数据库
1.Python3.x是使用pymysql库访问
2.Python2.x是使用mysqldb库访问
3.实例Python3
import pymysql
# 创建连接
conn = pymysql.connect(host='xxx.xxx.xxx.xxx', port='3306',user='name', passwd='123456', db='xxx',charset='utf8')
# 执行sql
cursor = conn.cursor()
sql = "SELECT * from *** WHERE app_names = '健康好水'"
cursor.execute(sql)
# 取出sql数据
data = cursor.fetchall()
print(data)
# 关闭连接
conn.close()
二.MySQL数据库端口
1.当端口不是默认端口3306的时候,需要在连接中传入端口号
1.1.例如:Port=3306
三.MySQL数据库编码问题
1.Mysql的编码设置为utf8,Python读取mysql表中的数据的时候,中文显示为什么?
1.1.因为Python读取后编码为unicode,在连接Mysql的时候,编码为utf8就好
2.当sql中有中文时,执行会报错
2.1.解决方式是在连接中传递编码方式:charset='utf8'