在Python中使用MySQL--PyMySQL的基本使用

PyMySQL的使用

  1. 安装

    sudo pip3 install pymysql
  2. 基本使用

    from pymysql import connect
    # 1.创建链接
    coon = connect()
    """
     * 参数host:连接的mysql主机,如果本机是'localhost'
     * 参数port:连接的mysql主机的端口,默认是3306
     * 参数user:连接的用户名
     * 参数password:连接的密码
     * 参数database:数据库的名称
     * 参数charset:通信采用的编码方式,推荐使用utf8
    """
    # 2.创建游标
    cur = conn.cursor()
    sql = 'select * from table_name;'
    count = cursor.execute(sql)  # count为sql语句影响数据的行数
    # 3.取出数据
    content = cur.fetchall()  # fetchone()取出一行数据
    # 4.关闭游标
    cur.close()
    # 5.关闭连接
    conn.close()

     

  3. 其他方法

    • conn.commit()提交

    • conn.rollback()回滚

      配合try方法使用

  4. 防注入

    防止用户提交带有恶意的数据与sql语句拼接,从而影响sql语句的语义,导致数据泄露。

    • 参数化:将参数在sql语句中使用%s占位,将所需参数存入一个列表中,将该列表作为第二个参数传给execute方法

      par = ['name', 'age']
      cursor.execute('select %s,%s from table_name;', par)

       

posted @ 2019-11-18 22:04  木心95  阅读(233)  评论(0编辑  收藏  举报