zoukankan      html  css  js  c++  java
  • MySQL数据库篇之pymysql模块的使用

    主要内容:

      一、pymysql模块的使用

      二、pymysq模块增删改查

    1️⃣  pymsql模块的使用

      1、前言:之前我们都是通过MySQL自带的命令行客户端工具mysql来操作数据库,

      那如何在python程序中操作数据库呢?这就用到了pymysql模块,该模块本质就是一个套接字

      客户端软件,使用前需要事先安装。

    pip3 install pymysql

      2、实例:

    #!/user/bin/env python3
    # -*- coding:utf-8-*-
    # write by congcong
    
    import pymysql
    
    user = input('user>>:').strip()
    pwd = input('password>>:').strip()
    # 建立链接
    conn=pymysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='0514',
        db='db6',
        charset='utf8'
    )
    # 拿到游标
    cursor = conn.cursor() # 执行完毕后返回的结果集默认以元祖显示
    # 执行sql语句
    sql = 'select * from userinfo where name="%s" and pwd="%s"' %(user,pwd)
    print(sql)
    rows = cursor.execute(sql) # 受影响的行数,execute表示执行
    
    cursor.close() # 关闭游标
    conn.close() # 关闭链接
    
    if rows:
        print('登陆成功!')
    else:
        print('失败...')
     

    注意:

      这种方式存在很大的隐患,即sql注入问题,可绕过密码登录,如:cc1" -- hello 

    3、execute()之sql注入
      注意:符号--会注释掉它之后的sql,正确的语法:--后至少有一个任意字符
     user>>:cc1" -- hello    # “ 对应左边的左引号,”--“ 在sql语句中表示注释后面的语句,注意中间有空格
        password>>:
        select * from userinfo where name="cc1" -- hello" and pwd=""
        登陆成功!
    # 甚至可同时绕过用户名和密码,如:xxxx" or 1=1 -- hello
    '''
    user>>:xxx" or 1=1 -- hello     # or表示或,用户名满足任意一条件即可
    password>>:
    select * from userinfo where name="xxx" or 1=1 -- hello" and pwd=""
    登陆成功!
    '''

      上述程序的改进版如下:

    #!/user/bin/env python3
    # -*- coding:utf-8-*-
    # write by congcong
    
    import pymysql
    # 改进版如下:
    user = input('用户名>>:').strip()
    pwd = input('密码>>:').strip()
    # 建立链接
    conn = pymysql.connect(
        host='localhost',
        port= 3306,
        user = 'root',
        password = '0514',
        db='db6',
        charset = 'utf8'
    )
    # 拿到游标
    cursor = conn.cursor()
    # 执行
    sql = 'select * from userinfo where name=%s and pwd=%s'
    # print(sql)
    rows = cursor.execute(sql,(user,pwd))
    
    cursor.close()
    conn.close()
    if rows:
        print('welcome login!')
    else:
        print('failed...')

    2️⃣  pymysq模块增删改查

      1、插入数据

    #!/user/bin/env python3
    # -*- coding:utf-8-*-
    # write by congcong
    import pymysql
    
    #1、建链接
    conn = pymysql.connect(
        host = '127.0.0.1',  # 本地主机
        port = 3306, # mysql默认端口
        user = 'root',  # MySQL用户
        password = '0514', # 用户密码
        db = 'db6',   # 数据库
        charset = 'utf8'  # 字符编码
    )
    
    # 2、取游标
    cursor = conn.cursor()
    
    # 3、执行sql语句
    '''
    # 插入数据前
        mysql> select * from userinfo;
        +----+------+-----+
        | id | name | pwd |
        +----+------+-----+
        |  1 | cc1  | 123 |
        |  2 | hyt  | 456 |
        +----+------+-----+
        2 rows in set (0.00 sec)
        
    # 插入(增)
    sql = 'insert into userinfo(name,pwd) values(%s,%s)'
    # rows = cursor.execute(sql,('cc2','666')) # 插入单行语句
    rows = cursor.executemany(sql,[('hy1','514'),('hyt2','0514'),('cc2','666888')]) # 插入多条数据
    print(rows)
    
    # 插入数据后
        mysql> select * from userinfo;
        +----+------+--------+
        | id | name | pwd    |
        +----+------+--------+
        |  1 | cc1  |    123 |
        |  2 | hyt  |    456 |
        |  3 | cc2  |    666 |
        |  4 | hy1  |    514 |
        |  5 | hyt2 |    514 |
        |  6 | cc2  | 666888 |
        +----+------+--------+
        6 rows in set (0.00 sec)
    '''
    sql = 'insert into userinfo(name,pwd) values (%s,%s)'
    rows = cursor.executemany(sql,[('sc1','111'),('sc2','222')])
    print(rows) # 2
    # 查询表中最后一条数据的id,必须在插入后查询
    print(cursor.lastrowid) # 7,返回的数据是现在插入的数据起始id
    '''
    mysql> select * from userinfo;
    +----+------+-----+
    | id | name | pwd |
    +----+------+-----+
    | 1 | 0 | 123 |
    | 2 | hyt | 456 |
    | 3 | cc2 | 666 |
    | 7 | sc1 | 111 |
    | 8 | sc2 | 222 |
    +----+------+-----+
    5 rows in set (0.00 sec)
    '''
    
    
    conn.commit() # 更新数据表,更新后才能在查询插入后的结果
    
    cursor.close() # 关闭游标
    conn.close() # 关闭链接

      2、删除数据

    import pymysql
    
    #1、建链接
    conn = pymysql.connect(
        host = '127.0.0.1',  # 本地主机
        port = 3306, # mysql默认端口
        user = 'root',  # MySQL用户
        password = '0514', # 用户密码
        db = 'db6',   # 数据库
        charset = 'utf8'  # 字符编码
    )
    
    # 2、取游标
    cursor = conn.cursor()
    
    # 3、执行sql语句
    # 删除
    sql = 'delete  from userinfo where id=%s'
    # rows=cursor.execute(sql,6) # 删除一条
    rows=cursor.executemany(sql,[4,5,6]) # 删除多条
    
        mysql> select * from userinfo;
        +----+------+-----+
        | id | name | pwd |
        +----+------+-----+
        |  1 | cc1  | 123 |
        |  2 | hyt  | 456 |
        |  3 | cc2  | 666 |
        +----+------+-----+
        3 rows in set (0.00 sec)
    conn.commit() # 更新数据表

    cursor.close() # 关闭游标
    conn.close() # 关闭链接

      3、修改数据

    import pymysql
    
    #1、建链接
    conn = pymysql.connect(
        host = '127.0.0.1',  # 本地主机
        port = 3306, # mysql默认端口
        user = 'root',  # MySQL用户
        password = '0514', # 用户密码
        db = 'db6',   # 数据库
        charset = 'utf8'  # 字符编码
    )
    
    # 2、取游标
    cursor = conn.cursor()
    
    # 3、执行sql语句
    # 修改
    sql = 'update userinfo set name="cc" where id=%s '
    cursor.execute(sql,1)
    
        mysql> select * from userinfo;
        +----+------+-----+
        | id | name | pwd |
        +----+------+-----+
        |  1 | cc   | 123 |
        |  2 | hyt  | 456 |
        |  3 | cc2  | 666 |
        +----+------+-----+
        3 rows in set (0.00 sec)

    conn.commit() # 更新数据表

    cursor.close() # 关闭游标
    conn.close() # 关闭链接

      4、查询数据

    import pymysql
    
    #1、建链接
    conn = pymysql.connect(
        host = '127.0.0.1',  # 本地主机
        port = 3306, # mysql默认端口
        user = 'root',  # MySQL用户
        password = '0514', # 用户密码
        db = 'db6',   # 数据库
        charset = 'utf8'  # 字符编码
    )
    
    # 2、取游标
    cursor = conn.cursor()
    
    # 3、执行sql语句
    查询数据
    
    cursor = conn.cursor(pymysql.cursors.DictCursor) # 取游标,数据以字典形式取出
    sql = 'select * from userinfo'
    rows = cursor.execute(sql) # 执行sql语句,返回sql影响成功的行数rows,将结果放入一个集合,等待被查询
    # rows = cursor.execute('select * from userinfo;')
    # fetchone 一次取一条数据
    # print(cursor.fetchone()) # {'id': 1, 'name': '0', 'pwd': 123}
    # print(cursor.fetchone())
    # print(cursor.fetchone())
    # print(cursor.fetchone()) # 不会报错,取完后返回None
    
    # fetchmany 一次取多条数据,超过数据条数大小时不报错
    #print(cursor.fetchmany(2))  # [{'id': 1, 'name': '0', 'pwd': 123}, {'id': 2, 'name': 'hyt', 'pwd': 456}]
    
    # fetchall 一次取出全部数据
    # print(cursor.fetchall())
    
    # cursor.scroll(1,mode='absolute') # 相对绝对位置移动,从头向后移动一条数据
    # print(cursor.fetchone()) # {'id': 2, 'name': 'hyt', 'pwd': 456}
    print(cursor.fetchone())
    cursor.scroll(1,mode='relative') # 相对当前位置移动,从上一条查询数据向后移动一条数据
    print(cursor.fetchone())
    '''
    conn.commit() # 更新数据表
    
    cursor.close() # 关闭游标
    conn.close() # 关闭链接
  • 相关阅读:
    JavaScript 的核心机制——event loop(最易懂版)
    关于敏捷讨论的感想
    前端,如何更优雅的面对异步
    广告行业中那些趣事系列10:推荐系统中不得不说的DSSM双塔模型
    书中自有黄金屋系列7:读《博世宁医学通识讲义》
    广告行业中那些趣事系列9:一网打尽Youtube深度学习推荐系统
    书中自有黄金屋系列6:读《浪潮之巅》-下篇
    书中自有黄金屋系列6:读《浪潮之巅》-上篇
    广告行业中那些趣事系列8:详解BERT中分类器源码
    书中自有黄金屋系列5:读《正面管教》
  • 原文地址:https://www.cnblogs.com/schut/p/9070119.html
Copyright © 2011-2022 走看看