zoukankan      html  css  js  c++  java
  • 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')
  • 相关阅读:
    强大的Resharp插件
    配置SPARK 2.3.0 默认使用 PYTHON3
    python3 数据库操作
    python3 学习中的遇到一些难点
    log4j的一个模板分析
    MYSQL内连接,外连接,左连接,右连接
    rabbitmq实战记录
    领域模型分析
    分布式系统学习笔记
    阿里开发规范 注意事项
  • 原文地址:https://www.cnblogs.com/echo-up/p/9754417.html
Copyright © 2011-2022 走看看