zoukankan      html  css  js  c++  java
  • pymysql的使用

    一: 安装pymysql

    pip3 install pymysql

    二: 查询操作

    import pymysql
    
    # 打开数据库连接
    db = pymysql.connect(host='localhost', user='root', password='123456', db='userinfo', port=3306)
    
    # 使用cursor()方法获取操作游标
    cur = db.cursor()
    
    #1, 查询操作
    # 编写sql,查询语句 s_info 对应的表名
    sql = "select * from s_info"
    try:
        cur.execute(sql)    # 执行sql语句
    
        # results = cur.fetchall()
    
        # 获取一行
        # result_one = cur.fetchone()
        # print(result_one)
    
        # 获取多个
        result_many = cur.fetchmany(3)
        print(result_many)
        # print(results) # 返回所有的数据一元组套元组的形式
        # print("id", "name", "pwd")
        # #遍历结果
        # for row in results:
        #     id = row[0]
        #     name = row[1]
        #     password = row[2]
        #     print(id, name, password)
    except Exception as e:
        raise e
    finally:
        db.close()
    查询

    三: 插入操作

    import pymysql
    
    #2 插入操作
    db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='userinfo')
    
    # 使用游标
    cur = db.cursor()
    
    sql_insert =  "insert into s_info(name, pwd) values('egon', '456')"
    
    try:
        cur.execute(sql_insert)
    
        db.commit()
    except Exception as e:
        db.rollback()
        raise e
    finally:
        cur.close()
        db.close()
    插入数据

    四: 修改操作

    import pymysql
    
    # 获取数据库
    db = pymysql.connect(host='localhost', user='root', password='123456', db='userinfo', port=3306)
    
    # 获取游标
    cur = db.cursor()
    
    # sql改语句
    sql = "update s_info set name=%s where id=7"
    try:
        cur.execute(sql, "egon")
        db.commit()
    except Exception as e:
        raise e
    finally:
        cur.close()
        db.close()
    改操作

    五: 删除操作

    import pymysql
    
    db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='userinfo')
    
    cur = db.cursor()
    
    sql = "delete from s_info where id=1"
    
    try:
        cur.execute(sql)
        db.commit()
    except Exception as e:
        raise e
    finally:
        cur.close()
        db.close()
    View Code
  • 相关阅读:
    如何操作3D中的摄像机
    软件开发的未来,是MDA/MDD/面向模式/Plugin IDE吗?[转]
    Hibernate3一个不错的入门介绍
    C#中的== Equals 与 Java 的== Euqals
    The Attributes property of a ListItem control only works within an HtmlSelect control
    WebWork 与 Struts
    会计基本流程
    常用 js 函数
    SQL中的sysobjects与syscolumns
    一个Struts2的的辅助工具
  • 原文地址:https://www.cnblogs.com/chenrun/p/9580382.html
Copyright © 2011-2022 走看看