• 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
  • 相关阅读:
    pytorchdeeplabxception Public 分割模型训练
    浪潮服务器 使用远控安装centos图文步骤
    某系统开发全程记录(20220608)
    计算机网络协议
    使用ACME工具来生成TSL证书
    数据库日志文件ldf过大解决方案
    20192404 202120222 《网络与系统攻防技术》实验八实验报告
    收缩日志
    .NET Core WebAPI文件下载+断点续传+取消下载
    以管理员身份运行WinForm程序
  • 原文地址:https://www.cnblogs.com/chenrun/p/9580382.html
Copyright © 2020-2023  润新知