增
import pymsql
- 连接数据库
conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='123456',database='db3',charset='utf8')
- 获取光标
cursor = conn.cursor()
data = [('小明',123),('小花',456)]
sql = "insert into user(name,password) values(%s,%s);"
- 执行sql语句
cursor.execute(sql,['王五','888'])
批量执行多条sql语句 cursor.executemany(sql,data)
- 获取新增数据id
print(cursor.lastrowid)
- 提交数据
conn.commit()
- 关闭光标,数据库连接
cursor.close()
conn.close()
删
sql = "delete from user where name=%s;"
cursor.execute(sql,['小明'])
改
sql = "update user set password=%s where name=%s;"
cursor.execute(sql,['888','张三'])
查
以字典的格式返回数据
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
sql = "select * from user;"
cursor.execute(sql)
- fetchall() 获取所有结果
ret = cursor.fetchall()
- fetchone() 获取一条结果
ret = cursor.fetchone()
- fetchmany() 获取指定数量的结果
ret = fetchmany(2)
数据回滚
try:
cursor.execute(sql)
conn.commit()
except Exception as e:
conn.rollback()
移动光标
- 光标按绝对位置移动
cursor.scroll(1,model='absolute') - 光标按相对位置移动
cursor.scroll(1,model='relative')