Loading

pymysql介绍

PyMySQL介绍

【1】简洁

  • 纯Python实现的模块,可以与Python代码兼容衔接,并也几乎兼容MySQL-python。
  • 遵循 Python 数据库 API v2.0 规范。
  • 官网:https://zetcode.com/python/pymysql/

【2】安装

  • 通过pip install pymsql安装

【3】用法

# 导入模块
import pymysql
from pymysql.cursors import DictCursor

# 创建连接对象
conn = pymysql.connect(
    user='root',
    password='123456',
    host='127.0.0.1',
    port=3306,
    database='db1',
    cursorclass=DictCursor
)

cursors = conn.cursor()  # 创建一个游标,以此来操作数据库
sql = '' # 定义一个sql语句
res1 = cursors.execute(sql)  # 提交sql语句,会返回影响的行数

# 查询类sql语句
res1 = cursors.fetchone()  # # 取一条数据
res2 = cursors.fetchall()  # 取所有数据
res3 = cursors.fetchmany(size=)  # 取指定条数据

# 修改类sql语句 需要通过连接对象提交
conn.commit()

【4】模板

import pymysql
from pymysql.cursors import DictCursor

# 创建一个类
class MySQLHandler:
    def __init__(self):
        self.conn = pymysql.connect(
            host='127.0.0.1',
            port=3306,
            user='root',
            password='123456',
            cursorclass=DictCursor,
            database='db1'
        )
        self.course = self.conn.cursor()
	# 查询一条记录
    def search_one(self, sql):
        self.course.execute(sql)
        result = self.course.fetchone()
        return result
	# 查询所有记录
    def search_all(self, sql):
        self.course.execute(sql)
        result = self.course.fetchall()
        return result
	# 查询多条记录
    def search_many(self, sql, size):
        self.course.execute(sql)
        result = self.course.fetchmany(size=size)
        return result
	# 插入记录
    def insert_data(self, table_name, **kwargs):
        if kwargs:
            sql = f'INSERT INTO {table_name} ({", ".join(kwargs.keys())}) VALUES {tuple(kwargs.values())}'
        else:
            sql = f'INSERT INTO {table_name} () VALUES ()'
        print(f'当前SQL语句 :>>>> {sql}')
        self.conn.commit()
        return self.course.execute(sql)
	# 删除记录
    def update_data(self, sql):
        self.course.execute(sql)
        self.conn.commit()
        return self.course.execute(sql)
	# 关闭连接
    def close(self):
        self.course.close()
        self.conn.close()


a = MySQLHandler()

sql = 'select * from test;'
print(a.search_many(sql=sql, size=3))

posted @ 2024-03-24 17:04  HuangQiaoqi  阅读(26)  评论(0编辑  收藏  举报