# 使用Python建立SQLite DB with SQLAlchemy ###### tags: `SQL` Copyright 2021, [月下麒麟](https://hackmd.io/@YMont/note-catalog) --- ## Objectives 如臨時遇到要用一個<u>資料庫做測試</u>, 但手動建立會比較慢且沒效率, 於是,想到讓<u>程式自動去建立一個框架(資料庫)</u>, 只要稍微修改DB名稱、DB tablename...等,僅需變更幾個小地方 執行Python程式,就會獲得一個SQLite資料庫與其內容 ## Requirements Windows install: **Python SQLite Studio** Windows cmd: **pip install Flask pip install SQLAlchemy** ## Source Code ```python= from flask import Flask from flask_sqlalchemy import SQLAlchemy import os from random import randint # create an instance in the flask frame app = Flask(__name__) # SQLite datebase link app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = r'sqlite:///D:\database\example.db' app.config['SECRET_KEY'] = os.urandom(10) # connect app with SQLAchemy(SQLite) db = SQLAlchemy(app) # create data list and column class DBFrame(db.Model): __tablename__ = "tablename" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60)) grade = db.Column(db.Integer) def __init__(self, name, grade): self.name = name self.grade = grade def __repr__(self): return '< {} , {} , {} >'.format(self.id, self.name, self.grade) def add_data(): # You can change that what kind of database you need for x in range(1,5): item = DBFrame('John',randint(60,100)) db.session.add(item) for x in range(1,5): item = DBFrame('Mary',randint(60,100)) db.session.add(item) for x in range(1,5): item = DBFrame('Edgar',randint(60,100)) db.session.add(item) # database commit is a important step db.session.commit() if __name__ == "__main__": db.create_all() add_data() ``` 故如上程式碼,所要更改的地方有: 路徑>> D:\database\example.db 資料表>> "testname" 欄位名稱>> name, grade 資料內容>> add_data()函式 另外, **SQLAlchemy是個Python所應用的資料庫框架, 可以讓你省去不少時間連結資料庫...等瑣碎事情, 所以,<u>熟悉SQLAlchemy的語法</u>應用會帶來許多的方便**。 reference:[[Flask教學] Flask-SQLAlchemy 資料庫操作-ORM篇(二)](https://www.maxlist.xyz/2019/10/30/flask-sqlalchemy/) ## Summary 在Python的IDLE執行程式碼後,並不會顯示出任何文字或對話, 需要開啟SQLite確認,如下圖: ![](https://i.imgur.com/Q8fYdbT.png) 這樣就建立成功了~ (今日簡短紀錄一下)