# 管理資料庫 ###### tags: `程式學習與問題總集` ###### tags: `人生苦短,我學Python` ## 安裝模組 * 在連線前,必須先安裝這2個模組 ```python= pip install -U flask_sqlalchemy pip install -U psycopg2 ``` ## ORM的使用 * ORM的概念是將資料庫的內容映射為物件,程式可以利用操作物件的方式對資料庫進行操作,而不直接使用SQL語法。 ![](https://i.imgur.com/mPR0msP.png) ## 設定資料庫連線 * 以PostgreSQL為例 ```python= from flask import Flask, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URL'] = 'postgresql://管理者帳號:管理者密碼@資料庫位址:5432/資料庫名稱' db = SQLAlchemy(app) ``` * 定義資料模型,範例 ```python= class 類別名稱(db.Model): __tablename__ = '資料庫名稱' 主欄位索引 = db.Column(db.integer, primary_key = True) 欄位名稱1 = db.Column(欄位型態1[, 欄位參數1, 欄位參數2]) def __init__(self, 欄位名稱1, ...): self.欄位名稱1 = 欄位名稱1 ``` * 資料型態 | Integer| int | 整數 | | -------- | -------- | -------- | | Float | float | 浮點數 | |String/Text|str|字串/長篇文字| |Boolean|bool|布林值| * 當資料模型定義完成,最後要用**db.create_all()**建立資料表物件。 * example ```python= from flask import Flask, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://admin:123456@127.0.0.1:5432/testdb' #app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) class students(db.Model): __tablename__ = 'students' sid = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(50), nullable = False) tel = db.Column(db.String(50)) addr = db.Column(db.String(200)) email = db.Column(db.String(100)) def __init__(self, name, tel, addr, email): self.name = name self.tel = tel self.addr = addr self.email = email @app.route('/') def index(): db.create_all() return '資料庫連線成功' if __name__ == '__main__': app.run() ``` * 結果 ![](https://i.imgur.com/ay0FYWc.png) * 打開testdb ![](https://i.imgur.com/bn9YZRW.png) * 右鍵,選擇Properties ![](https://i.imgur.com/LkYeSuE.png) * General標籤(資料表名稱,擁有者) ![](https://i.imgur.com/UndeL4L.png) * Colums標籤(資料欄位) ![](https://i.imgur.com/63YiLUR.png) {%hackmd S1DMFioCO %}