Pymysql使用方法如下
import pymysql
conn = pymysql.connect(host="localhost",port=3306,user="root",password="123456",charset="utf8")
cur = conn.cursor()
sql = 'select * from frist'
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
详细介绍如下
#安装mysql驱动
pip pymysql
#导入模块
import pymysql
#使用 connect 连接数据库 , 并创建conn对象
#密码是字符串类型,主机为本机地址
conn = pymysql.connect(host="localhost", user="root", port=3306, database="ceshi", charset="utf8", password="123456")
#创建游标 cur
cur = conn.cursor()
#执行SQL语句,注意外面的单引号与SQL双引号“引号区别
SQL = 'insert into frist(name,sex,age) values("caiyi","nan",20)'
SQL2 = 'select * from frist'
SQL3 = 'select name from frist where age>18'
cur.execute(SQL3)
#提交数据
conn.commit()
#取元组里面的值
fet = cur.fetchall()
for iter in fet:
print(iter)
#注意一定要关闭游标、连接
cur.close()
conn.close()
总结如下:
- 连接数据库
- 创建游标
- 对数据库进行增删改查
- 关闭游标与连接,释放资源
错误解析:
1. TypeError: object supporting the buffer API required
改:password="密码是字符串类型"
2. AttributeError: 'NoneType' object has no attribute 'encoding'
改:charset="编码为utf8"