mysql数据库模块的实现
时间: 2024-05-16 07:18:12 浏览: 21
MySQL 是一种关系型数据库管理系统,常用于存储数据。在 Python 中,我们可以使用 MySQL 客户端库来连接 MySQL 数据库,并进行增删改查等操作。
下面是一个简单的 MySQL 数据库模块实现,它包括连接数据库、创建表、插入数据、查询数据等基本操作:
```python
import mysql.connector
class MySQLDB:
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 create_table(self, table_name, columns):
cursor = self.connection.cursor()
columns_str = ', '.join([f'{col_name} {col_type}' for col_name, col_type in columns.items()])
cursor.execute(f'CREATE TABLE {table_name} ({columns_str})')
self.connection.commit()
def insert_data(self, table_name, data):
cursor = self.connection.cursor()
placeholders = ', '.join(['%s'] * len(data))
values = tuple(data.values())
columns = ', '.join(data.keys())
cursor.execute(f'INSERT INTO {table_name} ({columns}) VALUES ({placeholders})', values)
self.connection.commit()
def query_data(self, table_name, columns=None, where=None):
cursor = self.connection.cursor()
columns_str = '*' if columns is None else ', '.join(columns)
where_str = '' if where is None else f'WHERE {where}'
cursor.execute(f'SELECT {columns_str} FROM {table_name} {where_str}')
results = cursor.fetchall()
return results
```
使用示例:
```python
# 连接数据库
db = MySQLDB(host='localhost', user='root', password='password', database='my_database')
db.connect()
# 创建表
columns = {'id': 'INT AUTO_INCREMENT PRIMARY KEY', 'name': 'VARCHAR(255)', 'age': 'INT'}
db.create_table('my_table', columns)
# 插入数据
data = {'name': 'John', 'age': 25}
db.insert_data('my_table', data)
# 查询数据
results = db.query_data('my_table')
for result in results:
print(result)
```
需要注意的是,此处使用了 `mysql-connector-python` 库来连接 MySQL 数据库。在使用之前需要先安装该库:
```
pip install mysql-connector-python
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)