Python - PyMysql

mysql 查询操作





import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='student', password='password', database='test',
                       charset='utf8')
# 创建游标对象
cursor = conn.cursor()
# 执行操作,返回受影响的行
n = cursor.execute("select id  from bs_user where username like '%python%'")
# 获得结果集中的一个数据,返回数据类型是一个元组
# result = cursor.fetchone()

# 获得结果集中的执行数据个数
# result = cursor.fetchmany(3)  # output: (('000123',), ('1000000',), ('10000010',))

# 获得结果集所有数据
result = cursor.fetchall()
print(result)

cursor.close()
conn.close()

cursor 的不同类型

创建连接时,通过 cursorclass 参数指定类型:

connection = pymysql.connect(host='localhost',
                             user='root',
                             password='root',
                             db='demo',
                             charset='utf8',
                             cursorclass=pymysql.cursors.DictCursor)

也可以在创建游标时指定类型:

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

查询时,默认返回的数据类型为元组,可以自定义设置返回类型。支持5种游标类型:

  • Cursor: 默认,元组类型
  • DictCursor: 字典类型
  • DictCursorMixin: 支持自定义的游标类型,需先自定义才可使用
  • SSCursor: 无缓冲元组类型
  • SSDictCursor: 无缓冲字典类型

无缓冲游标类型,适用于数据量很大,一次性返回太慢,或者服务端带宽较小时

事务操作

ACID:
atomicity: 原子性
consistency: 一致性
isolation: 隔离性
durability: 持久性

更新操作一定要提交事务

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='student', password='password',
                       database='test', charset='utf8')

cursor = conn.cursor()

try:
    cursor.execute('insert into t_book (id, title, pub_date,`read`) values(null, "从入门到放弃2", "2022-01-19",1)')
    # 无异常提交事务
    # conn.commit()
except Exception as e:
    # 有异常回滚事务
    conn.rollback()
    print(e)
else:
    # 无异常提交事务
    conn.commit()
finally:
    cursor.close()
    conn.close()

指定游标的位置

import pymysql

conn = pymysql.connect(host='127.0.0.1', port=3306, user='student', password='password', database='test',
                       charset='utf8')

cursor = conn.cursor()
all_data = cursor.execute('select * from  t_book limit 10')
print(cursor.fetchone())
print(cursor.fetchone())
print(cursor.fetchone())

cursor.rownumber = 0  # 更改游标的位置

print(cursor.fetchone())

cursor.close()
conn.close()

# out:
"""
(3, '廊桥遗梦', datetime.date(2021, 5, 20), 89, 250, 0)
(4, '厚黑学', datetime.date(2022, 1, 11), 89, 250, 0)
(6, '孙子兵法', datetime.date(877, 10, 23), 89, 250, 0)
(3, '廊桥遗梦', datetime.date(2021, 5, 20), 89, 250, 0)
"""

工具类

"""
类方法:
get_conn(cls): 建立连接,获取连接对象
query_one(cls, sql): 查询一条数据
query_all(cls, sql): 查询全部数据
iud_data(cls, sql): 执行数据库增删改
"""
import pymysql


class DButils(object):

    @classmethod
    def get_conn(cls):
        conn = pymysql.connect(host='211.103.136.244', port=7061, user='student', password='iHRM_student_2021',
                               database='test_db',
                               charset='utf8')

        return conn

    @classmethod
    def close_resourse(cls, cursor, conn):
        cursor.close()
        conn.close()

    @classmethod
    def query_one(cls, sql):
        """查询一条数据"""

        conn = cls.get_conn()
        # 获得游标
        cursor = conn.cursor()
        # 执行查询
        cursor.execute(sql)
        # 取结果
        one = cursor.fetchone()
        cls.close_resourse(cursor, conn)
        # 返回结果
        return one

    @classmethod
    def query_all(cls, sql):
        # 获得连接
        conn = cls.get_conn()
        # 建立游标对象
        cursor = conn.cursor()
        # 执行查询
        n = cursor.execute(sql)
        # fetch结果
        data = cursor.fetchall()
        # 关闭连接
        cls.close_resourse(cursor, conn)
        # 返回结果
        return data

    @classmethod
    def iud(cls, sql):
        # 获得连接
        conn = cls.get_conn()
        # 建立游标
        cursor = conn.cursor()
        n = 0
        try:
            # 执行SQL
            n = cursor.execute(sql)
        except Exception as e:
            print(e)
            # 回滚
            conn.rollback()
        else:
            conn.commit()
        finally:
            cls.close_resourse(cursor, conn)
        return n


if __name__ == '__main__':
    result = DButils.query_one("select * from t_book where title = '剑来'")
    print(result)


查询时数据量大的时候的取值方式


官方文档:

https://github.com/PyMySQL/PyMySQL
https://pymysql.readthedocs.io/en/latest/user/index.html

参考:
https://cloud.tencent.com/developer/article/1989460?from=15425

posted @ 2022-01-18 19:36  chuangzhou  阅读(41)  评论(0编辑  收藏  举报