以类的形式写Python的MySQLDB
时间: 2024-09-22 21:03:11 浏览: 31
在Python中,你可以使用`mysql-connector-python`库,它是一个官方推荐的MySQL数据库连接模块,允许你通过面向对象的方式来操作MySQL。以下是一个基本的类形式的示例,展示了如何使用该库建立一个MySQL数据库连接:
```python
import mysql.connector
class MySQLDatabase:
def __init__(self, host, user, password, database):
self.conn = None
self.connect_params = {
"host": host,
"user": user,
"password": password,
"database": database
}
def connect(self):
try:
self.conn = mysql.connector.connect(**self.connect_params)
print("Connected to MySQL")
except mysql.connector.Error as err:
print(f"Error connecting to MySQL: {err}")
def close(self):
if self.conn is not None:
self.conn.close()
print("Disconnected from MySQL")
def execute_query(self, query):
cursor = self.conn.cursor(dictionary=True) # 使用字典模式获取查询结果
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
return result
# 使用示例
db = MySQLDatabase("localhost", "root", "password", "test_database")
db.connect() # 连接到数据库
query = "SELECT * FROM users"
results = db.execute_query(query)
for row in results:
print(row)
db.close()
阅读全文