zoukankan      html  css  js  c++  java
  • pymysql使用

    pymysql安装

    pip install pymysql

    基本使用

    1.创建数据库链接

    connect = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='123456',
        database='autotest'
    )

    2.创建游标

    sql语句的执行在代码中必须通过游标来进行,所以先要创建游标对象;

    cur = connect.cursor()

    3.通过execute()函数执行sql语句;

    cur.execute("select * from user_info;")

    4.读取操作

    # 读取一行数据
    value = cur.fetchone()
    print(value)
    # 当再次使用fetchone()时,因为是游标形式,所以会自动读取第二行
    value2 = cur.fetchone()
    print(value2)
    # 获取多行数据
    value3 = cur.fetmany(3)
    print(value3)
    # 获取所有数据
    value4 = cur.fetchall()
    print(value4)

    5.使用增删改时需要进行提交操作

    #
    sql_insert = "insert into autotest_user(user_name,user_sex,user_age) value(%s,%s,%s);"
    data=[
        ('zhao', '',24),
        ('qian', '',23),
        ('sun', '',22)
    ]
    cursor.executemany(sql_insert, data)
    
    #
    sql_delete = "delete from autotest_user where user_name=%s;"
    username = 'jiang'
    cursor.execute(sql_delete,[username])
    
    #
    sql_update = "update autotest_user set user_name=%s where user_name=%s;"
    cursor.execute(sql_update,['zhao','li'])
    
    # 需要提交
    connect.commit()

     6.关闭数据库

    # 关闭连接
    cursor.close()
    connect.close()

    备注:使用增的时候,数据库插入的是int,不要使用%d格式化操作字符,统一使用%s

    设置游标类型

    Cursor:默认,元组类型

    DictCursor:字典类型

    DictCursorMixin:支持自定义的游标类型,需先自定义才可以使用

    SSCursor:无缓冲元组类型

    SSdictCursor:无缓冲字典类型

    方法一:在创建数据库链接时定义

    # 创建数据库连接
    connect = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='123456',
        database='autotest',
        cursorclass=pymysql.cursors.DictCursor
    )

     方法二:设置游标时即可更改游标类型

    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)

    防止sql注入

      参数化语句在执行sql语句时,不要直接将数据写入sql语句,而是通过格式化操作字符将需要写入的数据进行参数化拼接,以避免SQL注入

    sql_select = 'select %s from %s;'% ("user_name","autotest_user")
  • 相关阅读:
    easyui-datetimebox设置默认时分秒00:00:00
    分页工具类的封装
    关于查询排序DTO的封装
    android签名生成和发布
    android httpclient 设置超时
    Eclipse 模拟http 请求插件Rest Client
    volley 发送post请求
    mac book 华为C8815不能debug
    android一些小技巧
    PS相关技术
  • 原文地址:https://www.cnblogs.com/ClownAlin/p/13209587.html
Copyright © 2011-2022 走看看