以下是一个简洁的MySQL帮助类示例:
import mysql.connector
class MySQLHelper:
def __init__(self, host, username, password, database):
self.host = host
self.username = username
self.password = password
self.database = database
self.connection = None
self.cursor = None
def connect(self):
self.connection = mysql.connector.connect(
host=self.host,
user=self.username,
password=self.password,
database=self.database
)
self.cursor = self.connection.cursor()
def disconnect(self):
if self.connection.is_connected():
self.cursor.close()
self.connection.close()
def execute_query(self, query):
self.cursor.execute(query)
results = self.cursor.fetchall()
return results
def execute_update(self, query):
self.cursor.execute(query)
self.connection.commit()
return self.cursor.rowcount
使用示例:
# 创建MySQLHelper实例
helper = MySQLHelper("localhost", "root", "password", "mydatabase")
# 连接到数据库
helper.connect()
# 执行查询
results = helper.execute_query("SELECT * FROM mytable")
# 执行更新
rows_affected = helper.execute_update("UPDATE mytable SET column1='value1' WHERE id=1")
# 断开连接
helper.disconnect()
这个MySQL帮助类提供了连接到MySQL数据库、执行查询和更新操作的功能,可以根据需要进行扩展和修改。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站