写一个类,可以创建数据库表,可自定义字段数据类型、长度、默认值
时间: 2023-01-29 15:12:10 浏览: 70
这是一个示例类,用于创建数据库表,可自定义字段数据类型、长度和默认值:
```python
import mysql.connector
class TableCreator:
def __init__(self, table_name, fields):
self.table_name = table_name
self.fields = fields
def create_table(self):
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
cursor = connection.cursor()
field_definitions = []
for field in self.fields:
field_name = field['name']
field_type = field['type']
field_length = field.get('length')
default_value = field.get('default')
definition = f"{field_name} {field_type}"
if field_length:
definition += f"({field_length})"
if default_value:
definition += f" DEFAULT {default_value}"
field_definitions.append(definition)
create_table_query = f"CREATE TABLE {self.table_name} ({','.join(field_definitions)})"
cursor.execute(create_table_query)
connection.commit()
cursor.close()
connection.close()
```
使用方法:
```python
fields = [
{'name': 'id', 'type': 'INT', 'length': 11, 'default': 'NULL'},
{'name': 'name', 'type': 'VARCHAR', 'length': 255, 'default': 'NULL'},
{'name': 'age', 'type': 'INT', 'length': 3, 'default': 'NULL'},
]
table_creator = TableCreator('users', fields)
table_creator.create_table()
```
这将创建一个名为“users”的表,其中包含三个字段:“id”、“name”和“age”。这些字段的数据类型和长度将根据指定的参数进行设置,并可指定默认值。
注意:在运行上述代码之前,需要先安装 `mysql-connector-python` 库。可以使用以下命令安装:
```bash
pip install mysql-connector-python
```