在Python中,创建表通常与数据库相关。以下是使用不同数据库和库创建表的方法:
使用MySQL数据库
1. 安装MySQLdb库:
pip install mysqlclient
2. 创建数据库和表的示例代码:
import MySQLdb连接数据库db_config = {'host': '192.168.16.70','port': 3306,'user': 'root','passwd': '','db': 'students','charset': 'utf8'}try:cnx = MySQLdb.connect(db_config)except Exception as e:raise efinally:cnx.close()创建表student_table = """CREATE TABLE student (stdid INT PRIMARY KEY NOT NULL,stdname VARCHAR(100) NOT NULL,gender ENUM('M', 'F'),agent INT);"""course_table = """CREATE TABLE course (couid INT PRIMARY KEY NOT NULL,cname VARCHAR(100) NOT NULL,tid INT NOT NULL);"""score_table = """CREATE TABLE score (sid INT PRIMARY KEY NOT NULL,cid INT NOT NULL,score FLOAT,FOREIGN KEY (cid) REFERENCES course(couid));"""执行创建表的SQL语句with cnx.cursor() as cursor:for table in [student_table, course_table, score_table]:cursor.execute(table)cnx.commit()
使用SQLAlchemy和Flask
1. 安装相关库:
pip install flask-mysqldbpip install flaskpip install flask_sqlalchemy
2. 创建数据库和表的示例代码:
from flask import Flaskfrom flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@127.0.0.1:3306/flask_mysql'app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = Truedb = SQLAlchemy(app)class Config(object):SQLALCHEMY_DATABASE_URI = 'mysql://root:root@127.0.0.1:3306/flask_mysql'SQLALCHEMY_TRACK_MODIFICATIONS = Trueapp.config.from_object(Config)创建数据库模型类,对应一张模型表class Role(db.Model):__tablename__ = 'tbl_roles'id = db.Column(db.Integer, primary_key=True)
以上代码展示了如何使用Python连接MySQL数据库并创建表,以及使用Flask和SQLAlchemy框架创建数据库表的方法。请根据你的具体需求选择合适的方法和库。

