zoukankan      html  css  js  c++  java
  • 数据库入门-pymysql模块的使用

    一、pymysql模块安装

    由于本人的Python版本为python3.7,所以用pymysql来连接数据库(mysqldb不支持python3.x)

    方法一:

    #在cmd输入
    pip3 install pymysql

    方法二(pycharm IDE):

    [File] >> [settings] >> [Project: study] >> [Project Interpreter] >>点击右上角“+”号,搜索框输入“pymysql”>> [Install按钮]

     二、连接数据库

    import pymysql
    # 创建链接得到一个链接对象
    conn = pymysql.Connect(
        host="127.0.0.1",    # 数据库服务器主机地址
        user="root",  # 用户名
        password="123456", # 密码
        database="test", #数据库名称
        port=3306, # 端口号 可选 整型
        charset="utf8" # 编码  可选
    )

    还可以使用函数的形式连接数据库:

    import pymysql
    
    def connect_mysql():
        db_info = {
            'host':'192.168.13.253',
            'user':'zfj',
            'password':'123',
            'port':3306,
            'database':'day40',
            'charset':'utf8'
        }
        try:
            db = pymysql.Connect(**db_info)
            print('连接成功!')
        except Exception as e:
            print('e')
        return db
    
    if __name__ == '__main__':
        db = connect_mysql()
    函数的形式

    三、操作数据库

    1.连接对象的常用方法

    commit()#提交稳定存储的更改
    rollback()#回滚当前事务
    autocommit_mode=无 #指定的自动提交模式。无表示使用服务器默认值。

    要想操作数据库必须先建立游标对象,不需要自己创建调用数据库对象下面的cursor方法就可以了

    2.游标对象

    创建游标:

    db = pymysql.connect(config)  # 创建数据库链接对象
    cus = db.cursor     # 创建游标对象
    print(dir(cus))     # 查看游标的方法

    游标常用方法:

    cus.cursor()   #创建游标对象
    cus.close()  #关闭游标对象
    
    cus.excute(query,args=None)  #执行查询
        参数:    
            query(str) - 要执行的查询。
            args(元组,列表或字典) - 与查询一起使用的参数。(可选的)
        返回:受影响的行数
        返回类型:INT
    
    executemany(查询,args ) #针对一个查询运行多个数据
        参数:    
            query - 要在服务器上执行的查询
            args - 序列或映射的序列。它用作参数。
    此方法可提高多行INSERT和REPLACE的性能。否则它等同于使用execute()循环遍历args。
    
    cus.fetchone()  #获取下一行
    cus.fetchall()   #获取所有行
    cus.fetchmany(size =None)  #获取几行
                

    注:sql必须是字符串类型

    3.示例

    import pymysql
    # 创建链接得到一个链接对象
    conn = pymysql.Connect(
        host="127.0.0.1",    # 数据库服务器主机地址
        user="root",  # 用户名
        password="admin", # 密码
        database="day42", #数据库名称
        port=3306, # 端口号 可选 整型
        charset="utf8" # 编码  可选
    )
    # 获取游标对象  pymysql.cursors.DictCursor指定 返回的结果类型 为字典  默认是元祖类型
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    
    # # 添加数据
    # res = cursor.execute("insert into emp values(100,'胡歌','男',30,1,'job',60000)")
    # if res:
    #     print("插入成功")
    # else:
    #     print("插入失败")
    
    
    # 提交修改   因为pymysql 模块默认是启用事务的  你的sql语句 如果不提交 相当于没有执行
    
    # conn.commit()
    # res = cursor.execute("drop database day42")
    
    
    # res = cursor.execute("delete from t1 where id = 1")
    # print(res)
    
    try:
        cursor.execute("update moneyTable set money = money - 50 where name = '小明'")
        #如果小花的账户出问题了 无法更新数据 那就需要回滚
        cursor.execute("update moneyTable set money = money + 50 where name = '小花'")
        conn.commit()
    except:
        conn.rollback()
        
    cursor.close()
    conn.close()
    
    #  小明有100块 准备给小花转50
    # update moneyTable set money = money - 50 where name = "小明";
    # 发生一些别错误  如果发生了错误 就执行撤销操作 rollback;
    # update moneyTable set money = money + 50 where name = "小花";
    View Code

    四、安全问题

    如何保证数据安全是近几年来火热的主题之一,这里不细讲,就说一些和pymysql相关的sql注入攻击。

    #sql = "select *from user where user = '%s' and pwd = '%s';" % (input("input userName"),input("input password"))
    
    # 当用户输入的用户名为字符串 为 yy' --   时
    # 最终产生的sql  select *from user where user = 'yy' -- ' and pwd = '987657890';
    # -- 用于mysql注释  意思是 后面的内容忽略掉
    # 从而导致 密码是否正确都能登录成功
    # "select *from user where user = 'axxax' or 1=1;

    那python是如何避免普通的sql注入的呢?

    通过excute函数,将需要传的参数放到arg参数中,让pymysql帮你屏蔽

    count = cursor.execute("select *from user where user = %s and pwd = %s;",args=(input("user"),input("pwd")))
    
    print(count)
    if count:
        print("login success")
    else:
        print("login error")
    
    cursor.close()
    conn.close()

    读者想要学习更多关于安全的内容可以关注“实验吧”学习:http://www.shiyanbar.com/

    部分参考 pymysql文档:https://pymysql.readthedocs.io/en/latest/index.html

    连接对象规范:https://www.python.org/dev/peps/pep-0249/#connection-objects

  • 相关阅读:
    virturalbox安装CentOS桥接网卡
    解决:Error:java: 无效的源发行版: 12
    maven下载失败,镜像配置,idea的maven下载配置
    linux压缩和解压缩命令
    Unable to allocate 130176KB bitmaps for parallel garbage collection for the requested 4165632KB heap.
    Docker,Linux,Kubernetes,postgres常用的命令行(持续更新)
    dropwizard问题记录1:如何进行mvn package打包,如何在项目目录下运行
    线程的并发工具类
    学信网改绑手机号码,但是忘记了老号码怎么办?利用node.js + puppeteer 跑脚本实现改绑手机号
    javascript事件循环与js执行机制
  • 原文地址:https://www.cnblogs.com/mangM/p/9665049.html
Copyright © 2011-2022 走看看