使用 Flask SQLAlchemy 的简单步骤:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
//employee.db database will get created in current python project
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///employee.db'
db = SQLAlchemy(app)
class Employee(db.Model):
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(20))
dept = db.Column(db.String(40))
要测试此代码,您需要运行 python shell
在 Python 外壳中运行:
//This is going to create table create_all() method
from one_to_many import db
db.create_all()
//This is going to insert data into table
from one_to_many import Employee
new_emp = Employee(name="Viraj",dept="IT")
db.session.add(new_emp)
db.session.commit()
//To check or retrieve data use this
show_all_data = Employee.query.all()
for i in show_all_data:
print(i.id,i.name,i.dept)