• pymysql


    一、pymysql

      pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同,我们今天来说下pymsql用法。MySQLdb的只有在python2 里面使用的,在python3里面需要用pymysql。

    二、安装pymysql

    pip3 install pymysql
    

     

    三、使用

      3.1 连接mysql

    # -*- coding: UTF-8 -*-
    
    import pymysql
    
    #  创建连接
    conn = pymysql.connect(host='172.16.200.49', port=3306,
                           user='bigberg', password='111111',
                           db='study')
    
    # 创建游标
    cursor = conn.cursor()
    
    # 执行SQL,并返回受影响行数
    effect_row = cursor.execute("select * from student")
    print(effect_row)
    # 执行SQL,并返回受影响行数
    # data = [
    #     ('S1','2018-04-21','M'),
    #     ('S2','2018-05-11','F'),
    #     ('S3','2018-04-25','M')
    # ]
    # sql = "insert into student (name,register_date,gender) values (%s,%s,%s)"
    # effect_row = cursor.executemany(sql,data)
    # 提交,不然无法保存
    conn.commit()
    
    # 关闭游标
    cursor.close()
    
    # 关闭连接
    conn.close()
    

      3.2 获取查询的数据

    # -*- coding: UTF-8 -*-
    
    import pymysql
    
    #  创建连接
    conn = pymysql.connect(host='172.16.200.49', port=3306,
                           user='bigberg', password='111111',
                           db='study')
    
    cursor = conn.cursor()
    sql = "select * from student where stu_id>3"
    cursor.execute(sql)
    # 获取第一行数据
    # result = cursor.fetchone()
    
    # 获取前n条数据
    # result = cursor.fetchmany(3)
    
    # 获取所有数据
    result = cursor.fetchall()
    print(result)
    
    conn.commit()
    cursor.close()
    conn.close()
    

      3.3 fetch数据类型

    import pymysql
    
    #  创建连接
    conn = pymysql.connect(host='172.16.200.49', port=3306,
                           user='bigberg', password='111111',
                           db='study',)
    # 游标设置为字典类型
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    

      

  • 相关阅读:
    java 并发性和多线程 -- 读感 (一 线程的基本概念部分)
    [翻译]Spring框架参考文档(V4.3.3)-第二章Spring框架介绍 2.1 2.2 翻译--2.3待继续
    java 内存模型
    控制反转容器& 依赖注入模式 ---读感。
    go json null字段的转换
    分布式数据库----数据同步
    java 多线程--- Thread Runnable Executors
    go runtime.Gosched() 和 time.Sleep() 做协程切换
    sql 里面 join in 的差别,join的用法
    定时器
  • 原文地址:https://www.cnblogs.com/bigberg/p/8310063.html
Copyright © 2020-2023  润新知