pymysql

import pymsql

  1. 连接数据库
  conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='123456',database='db3',charset='utf8')
  1. 获取光标
  cursor = conn.cursor()
  data = [('小明',123),('小花',456)]
  sql = "insert into user(name,password) values(%s,%s);"
  1. 执行sql语句
  cursor.execute(sql,['王五','888'])
  批量执行多条sql语句
  cursor.executemany(sql,data)
  1. 获取新增数据id
  print(cursor.lastrowid)
  1. 提交数据
  conn.commit()   
  1. 关闭光标,数据库连接
  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)
  1. fetchall() 获取所有结果
  ret = cursor.fetchall()
  1. fetchone() 获取一条结果
  ret = cursor.fetchone()
  1. fetchmany() 获取指定数量的结果
  ret = fetchmany(2)

数据回滚

try:
    cursor.execute(sql)
    conn.commit()
except Exception as e:
    conn.rollback()

移动光标

  1. 光标按绝对位置移动
    cursor.scroll(1,model='absolute')
  2. 光标按相对位置移动
    cursor.scroll(1,model='relative')
posted on 2018-10-08 15:03  旧巷子里的猫  阅读(99)  评论(0编辑  收藏  举报