Python操作Mysql数据库

持续更新中。。。

import json

import pymysql


class MyDataBase:
    def __init__(self, host: str, password: str, database: str = "czh", charset: str = "utf8"):
        self.host = host
        self.password = password
        self.database = database
        self.kwargs = {'user': "root", 'host': self.host,
                       "port": 3306, 'password': self.password,
                       'database': self.database,
                       "charset": charset}
        self.db = None
        self.cursor = None

    def connect(self):
        self.db = pymysql.connect(**self.kwargs)
        self.cursor = self.db.cursor()
        print("数据库已连接!")

    def create_table(self, table_name: str, kwargs: dict, reference=None):
        """
        :param table_name:
        :param kwargs: {"name":"varchar(30)","age":"tinyint"}
        :param reference: "foreign key(pid) references tb_name(id)"
        :return:
        """
        reference = f" ,{reference}" if reference else ""
        s = json.dumps(kwargs).replace(":", "").replace("{", "").replace("}", "").replace('"', "")
        sql = f"create table {table_name} ({s}{reference});"
        try:
            self.cursor.execute(sql)
            self.db.commit()
            print(f"数据表{table_name}创建成功!")
        except Exception as err:
            print(f"数据表{table_name}创建失败:{err}")

    def show_tables(self):
        if not self.get_tables():
            print("没有数据表!")
            return
        for table in self.get_tables():
            print(table)

    def get_tables(self):
        self.cursor.execute("show tables;")
        self.db.commit()
        res = self.cursor.fetchall()
        table_list = [i[0] for i in res]
        return table_list

    def desc_table(self, tb_name):
        self.cursor.execute(f"desc {tb_name};")
        self.db.commit()
        res = self.cursor.fetchall()
        for i in res:
            print(i, end="")
        print()

    def show_create(self, tb_name):
        self.cursor.execute(f"show create table {tb_name};")
        self.db.commit()
        res = self.cursor.fetchall()
        for i in res[0]:
            print(i)

    def delete_table(self, tb_name):
        if tb_name not in self.get_tables():
            print(f"没有数据表{tb_name}!")
            return
        self.cursor.execute(f"drop table {tb_name};")
        self.db.commit()
        print(f"数据表{tb_name}已删除")

    def alter_table(self, tb_name, action):
        """
        :param tb_name:
        :param action: add 字段名 数据类型/drop 字段名/modify 字段名 新数据类型/change 旧字段名 新字段名 新数据类型
        :return:
        """
        sql = f"alter table {tb_name} {action};"
        self.cursor.execute(sql)
        self.db.commit()
        print(f"数据表{tb_name}字段修改成功!")

    def insert_data(self, table_name: str, field: tuple, data):
        """
        :param table_name:表名
        :param field:字段
        :param data: [line one]
        :return:
        """
        fields = str(field).replace("'", "")
        ss = ",%s" * (len(field))
        sql = f"INSERT INTO {table_name} {fields} VALUES ({ss[1:]});"  # SQL语句
        try:
            self.cursor.execute(sql, data)
            self.db.commit()
        except Exception as err:
            print(f"存储失败:{err}")
            self.db.rollback()

    def select_table_record(self, tb_name: str, condition: str = None, targets: str = "*"):
        c = f" {condition}" if condition else ""
        sql = f"select {targets} from {tb_name}{c};"
        self.cursor.execute(sql)
        self.db.commit()
        res = self.cursor.fetchall()
        return list(res)

    def update_table_record(self, tb_name: str, condition: str = None, targets: str = None):
        """
        :param tb_name:
        :param targets:"age=10,score=22";"price=price+2"
        :param condition:"where id>1"
        :return:
        """
        c = f" {condition}" if condition else ""
        sql = f"update {tb_name} set {targets}{c};"
        self.cursor.execute(sql)
        self.db.commit()
        print(f"数据表{tb_name}记录更新成功")

    def delete_tabel_record(self, tb_name: str, condition: str = None, targets: str = None):
        c = f" {condition}" if condition else ""
        sql = f"delete from{tb_name}{c};"
        self.cursor.execute(sql)
        self.db.commit()
        print(f"数据表{tb_name}记录删除成功")

    def operate_table_record(self, tb_name: str, operation=None, condition: str = None, targets: str = "*"):
        c = f" {condition}" if condition else ""
        if operation == "select":
            sql = f"select {targets} from {tb_name}{c};"
            self.cursor.execute(sql)
            self.db.commit()
            res = self.cursor.fetchall()
            return list(res)
        elif operation == "update":
            sql = f"update {tb_name} set {targets}{c};"
        elif operation == "delete":
            sql = f"delete from{tb_name}{c};"
        self.cursor.execute(sql)
        self.db.commit()
        print(f"数据表{tb_name}记录操作成功")

    def close(self):
        self.cursor.close()
        self.db.close()
        print("数据库已断开!")


if __name__ == '__main__':
    MDB = MyDataBase("localhost", "123456")
    MDB.connect()
    args = {
        "id": "int primary key auto_increment",
        "bname": "varchar(50) not null",
        "author": "varchar(30) default '佚名'",
        "press": "varchar(128)",
        "price": "float unsigned",
        "comment": "text"
    }

    data = [
        ("边城", "沈从文", "机械工业出版社", 36, "小城故事多"),
        ("骆驼祥子", "老舍", "机械工业出版社", 43, "你是祥子么?"),
        ("茶馆", "老舍", "中国文学出版社", 55, "老北京"),
        ("呐喊", "鲁迅", "人民教育出版社", 71, "最后的声音"),
        ("朝花夕拾", "鲁迅", "中国文学出版社", 53, "好时光"),
        ("围城", "钱钟书", "中国文学出版社", 44, "你心中的围城是什么")
    ]
    field = ("bname", "author", "press", "price", "comment")
    try:
        for d in data:
            MDB.insert_data("books", field, d)
    except Exception as err:
        MDB.db.rollback()
        print(err)
    finally:
        MDB.close()

你可能感兴趣的:(python,数据库,mysql)