python 连接MySQL工具类

  1. 安装 mysql-connector-python
  2. 导入代码并修改数据库连接信息
import mysql.connector
from mysql.connector import Error


class MySQLDatabase:
    def __init__(self, host, user, password, db, port=3306):
        self.connection = None
        self.cursor = None
        try:
            self.connection = mysql.connector.connect(
                host=host,
                user=user,
                password=password,
                database=db,
                port=port
            )
            self.cursor = self.connection.cursor()
        except Error as e:
            print(f"连接到MySQL数据库时出错:{e}")

    def insert(self, query, values):
        if self.cursor:
            self.cursor.execute(query, values)
            self.connection.commit()
            return self.cursor.lastrowid
        else:
            print("操作失败:没有数据库连接。")
            return None

    def delete(self, query, values):
        if self.cursor:
            self.cursor.execute(query, values)
            self.connection.commit()
            return self.cursor.rowcount
        else:
            print("操作失败:没有数据库连接。")
            return None

    def update(self, query, values):
        if self.cursor:
            self.cursor.execute(query, values)
            self.connection.commit()
            return self.cursor.rowcount
        else:
            print("操作失败:没有数据库连接。")
            return None

    def select(self, query, values=None):
        if self.cursor:
            self.cursor.execute(query, values or ())
            return self.cursor.fetchall()
        else:
            print("操作失败:没有数据库连接。")
            return []

    def __del__(self):
        if self.cursor:
            try:
                self.cursor.close()
            except Error as e:
                print(f"关闭游标时出错:{e}")

        if self.connection:
            try:
                self.connection.close()
            except Error as e:
                print(f"关闭数据库连接时出错:{e}")


# 将db定义为全局变量
# db = MySQLDatabase('192.168.110.18', 'root', 'admin', 'check', port=3308)
# db.insert("INSERT INTO test (username, title) VALUES (%s, %s)", ('张三', 'values'))
# data = db.select("SELECT * FROM test")
# print(data)
# update_data = db.update("UPDATE test SET title = %s WHERE username = %s", ('[email protected]', 'JohnDoe'))
# db.delete("DELETE FROM test WHERE username = %s", ('张三',))

你可能感兴趣的:(python,mysql,开发语言)