python 执行mysql连接池 封装增删改查方法
作者:野牛程序员:2023-12-21 13:36:22python阅读 2361
使用Python执行MySQL连接池的封装增删改查方法可以提高数据库操作的效率。以下是一个简单的例子,使用mysql-connector-python
库和mysql-connector-python
库来实现连接池和基本的数据库操作。
import mysql.connector from mysql.connector import pooling # 数据库连接池配置 db_config = { "host": "your_host", "user": "your_user", "password": "your_password", "database": "your_database", } # 创建数据库连接池 connection_pool = pooling.MySQLConnectionPool(pool_name="mypool", pool_size=5, **db_config) # 封装数据库操作方法 class MySQLDB: @staticmethod def execute_query(query, params=None): connection = connection_pool.get_connection() cursor = connection.cursor(dictionary=True) try: cursor.execute(query, params) result = cursor.fetchall() return result finally: cursor.close() connection.close() @staticmethod def execute_update(query, params=None): connection = connection_pool.get_connection() cursor = connection.cursor() try: cursor.execute(query, params) connection.commit() return cursor.rowcount finally: cursor.close() connection.close() # 示例用法 select_query = "SELECT * FROM your_table WHERE column = %s" insert_query = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)" update_query = "UPDATE your_table SET column1 = %s WHERE column2 = %s" # 查询 result_set = MySQLDB.execute_query(select_query, ("value",)) print(result_set) # 插入 rows_affected = MySQLDB.execute_update(insert_query, ("value1", "value2")) print(f"Rows affected: {rows_affected}") # 更新 rows_updated = MySQLDB.execute_update(update_query, ("new_value", "old_value")) print(f"Rows updated: {rows_updated}")
请注意,需要根据实际情况替换示例中的your_host
、your_user
、your_password
、your_database
、your_table
、column1
、column2
等参数。此外,确保安装了mysql-connector-python
库:
pip install mysql-connector-python
这个例子中的MySQLDB
类封装了查询和更新操作,可以根据需要扩展该类以支持更多的数据库操作。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892