python MySQLdb数据库的增删改查

 一、详细步骤

1、定义数据库参数:数据库IP、用户名、密码、端口、编码格式以及数据库操作句柄;

class ConnectSQL:
    def __init__(self, host, user, password, port, charset="utf8"):
        self.host = host
        self.user = user
        self.password = password
        self.port = port
        self.charset = charset
        self.cursor = None

2、连接数据库:输入指定数据库名称,建立连接并返回数据库句柄;

    def connect(self, database):
        """
        Connect to the DataBase
        :param database:Database name
        :return:Database Handle
        """
        mysql = MySQLdb.connect(host=self.host,
                                user=self.user,
                                password=self.password,
                                port=self.port,
                                database=database,
                                charset=self.charset)
        self.cursor = mysql.cursor()
        return self.cursor

3、新增数据:输入数据表名,以元组形式输入表头和所需新增数据,然后将数据插入到数据表中;

    def add(self, table, keys: tuple, values: tuple):
        """
        Add data and insert it into the database
        :param table: table name
        :param keys:table header
        :param values:table data
        :return:
        """
        try:
            for _ in values:
                insert_sql = f"INSERT INTO {table}({','.join(_ for _ in keys)}) VALUES{_};"
                print(insert_sql)
                self.cursor.execute(insert_sql)
                return True
        except MySQLdb.IntegrityError:
            print('Insert fail, this message is exist')
            return False

4、查找数据表:根据数据表名和判断条件,查询数据表中相关数据;

    def search(self, table, sql_str: str):
        """
        Query data in the table
        :param table: table name
        :param sql_str: Database query conditions
        :return:
        """
        select_sql = F"SELECT * FROM {table} WHERE {sql_str};"
        print(select_sql)
        try:
            count = self.cursor.execute(select_sql)
            print(f'Found sql messages: %d' % count)
            if count != 0:
                for i in self.cursor.fetchall():
                    print(i)
            else:
                print("This message isn't exist")
            return count
        except MySQLdb.Error:
            print("Failed to query the data table. Procedure")
            return False

5、 修改数据表数据:输入数据表名,以元组形式输入表头和所需新增数据,然后将数据替换到数据表中;

    def edit(self, table, keys: tuple, values: tuple):
        """
        Modify or replace data in a data table
        :param table: table name
        :param keys: table header
        :param values: table data
        :return:
        """
        try:
            for _ in values:
                edict_sql = f"REPLACE INTO {table}({','.join(_ for _ in keys)}) VALUES{_};"
                print(edict_sql)
                self.cursor.execute(edict_sql)
            return True
        except MySQLdb.Error:
            print("Failed to modify the data table. Procedure")
            return False

6、 删除数据表数据:根据数据表和相关判断条件,删除数据表中指定数据;

    def delete(self, table, sql_str: str):
        """
        Delete data from the table
        :param table: table name
        :param sql_str: Database query conditions
        :return:
        """
        delete_sql = f"DELETE FROM {table} WHERE {sql_str};"
        print(delete_sql)
        try:
            self.cursor.execute(delete_sql)
            return True
        except MySQLdb.Error:
            return False

7、主函数

if __name__ == '__main__':
    hold_keys = ("id", "username", "age")
    hold_values = ((1, "zhangsan", 21), (2, "lisi", 23))
    hold = ConnectSQL(host=localhost, user="root", password="123456", port=3306)
    hold.connect('user')
    hold.add('tb_user', hold_keys, hold_values)
    hold.edit('tb_user', hold_keys, hold_values)
    hold.delete('tb_user', "id = 1")
    hold.search('tb_user', "id = 1")

二、汇总 

import MySQLdb


class ConnectSQL:
    def __init__(self, host, user, password, port, charset="utf8"):
        self.host = host
        self.user = user
        self.password = password
        self.port = port
        self.charset = charset
        self.cursor = None

    def connect(self, database):
        """
        Connect to the DataBase
        :param database:Database name
        :return:Database Handle
        """
        mysql = MySQLdb.connect(host=self.host,
                                user=self.user,
                                password=self.password,
                                port=self.port,
                                database=database,
                                charset=self.charset)
        self.cursor = mysql.cursor()
        return self.cursor

    def add(self, table, keys: tuple, values: tuple):
        """
        Add data and insert it into the database
        :param table: table name
        :param keys:table header
        :param values:table data
        :return:
        """
        try:
            for _ in values:
                insert_sql = f"INSERT INTO {table}({','.join(_ for _ in keys)}) VALUES{_};"
                print(insert_sql)
                self.cursor.execute(insert_sql)
                return True
        except MySQLdb.IntegrityError:
            print('Insert fail, this message is exist')
            return False

    def search(self, table, sql_str: str):
        """
        Query data in the table
        :param table: table name
        :param sql_str: Database query conditions
        :return:
        """
        select_sql = F"SELECT * FROM {table} WHERE {sql_str};"
        print(select_sql)
        try:
            count = self.cursor.execute(select_sql)
            print(f'Found sql messages: %d' % count)
            if count != 0:
                for i in self.cursor.fetchall():
                    print(i)
            else:
                print("This message isn't exist")
            return count
        except MySQLdb.Error:
            print("Failed to query the data table. Procedure")
            return False

    def edit(self, table, keys: tuple, values: tuple):
        """
        Modify or replace data in a data table
        :param table: table name
        :param keys: table header
        :param values: table data
        :return:
        """
        try:
            for _ in values:
                edict_sql = f"REPLACE INTO {table}({','.join(_ for _ in keys)}) VALUES{_};"
                print(edict_sql)
                self.cursor.execute(edict_sql)
            return True
        except MySQLdb.Error:
            print("Failed to modify the data table. Procedure")
            return False

    def delete(self, table, sql_str: str):
        """
        Delete data from the table
        :param table: table name
        :param sql_str: Database query conditions
        :return:
        """
        delete_sql = f"DELETE FROM {table} WHERE {sql_str};"
        print(delete_sql)
        try:
            self.cursor.execute(delete_sql)
            return True
        except MySQLdb.Error:
            return False


if __name__ == '__main__':
    hold_keys = ("id", "username", "age")
    hold_values = ((1, "zhangsan", 21), (2, "lisi", 23))
    hold = ConnectSQL(host=localhost, user="root", password="123456", port=3306)
    hold.connect('user')
    hold.add('tb_user', hold_keys, hold_values)
    hold.edit('tb_user', hold_keys, hold_values)
    hold.delete('tb_user', "id = 1")
    hold.search('tb_user', "id = 1")

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值