python 创建数据库类
时间: 2023-09-27 12:11:25 浏览: 75
以下是一个简单的 Python 类,用于创建和连接到 MySQL 数据库:
```python
import mysql.connector
class Database:
def __init__(self, host, user, password, database):
self.host = host
self.user = user
self.password = password
self.database = database
self.connection = None
def connect(self):
self.connection = mysql.connector.connect(
host=self.host,
user=self.user,
password=self.password,
database=self.database
)
def disconnect(self):
self.connection.close()
def execute(self, query, parameters=None):
cursor = self.connection.cursor()
cursor.execute(query, parameters)
return cursor.fetchall()
def commit(self):
self.connection.commit()
```
使用示例:
```python
db = Database("localhost", "root", "password", "example_db")
db.connect()
# 创建一个表
create_table_query = "CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))"
db.execute(create_table_query)
db.commit()
# 插入数据
insert_query = "INSERT INTO users (name, email) VALUES (%s, %s)"
parameters = ("John", "john@example.com")
db.execute(insert_query, parameters)
db.commit()
# 查询数据
select_query = "SELECT * FROM users"
results = db.execute(select_query)
print(results)
db.disconnect()
```
注意:在生产环境中,应该使用连接池来管理数据库连接,以避免连接泄漏和性能问题。
阅读全文