---
id: 194737d7-8f24-4f43-8303-f7837862a6ed
slug: flask-sqlalchemy-appendix-2
title: 工程 [2023_3_25] 附录文件「二」 - Flask SQLAlchemy
summary: ""
status: published
tags: []
cover: ""
version: 1
slug_source: manual
slug_locked: true
published_at: "2023-03-26T16:19:51+08:00"
created_at: "2023-03-26T16:19:51+08:00"
updated_at: "2026-01-07T18:11:15+08:00"
---

## 前言
本文主要介绍 Flask SQLAlchemy 的具体使用。

如需要了解 Flask 入门文档可跳转：
- [ 附录文件「一」 ](/2023/03/26/工程-2023-3-25-附录文件「一」-Flask-起步/)
- [ Flask官方文档 ](https://flask.palletsprojects.com/en/2.2.x/quickstart/)
- [ Flask-Sqlalchemy 官方文档](https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/)
## Setup
### Install MySQL/MariaDB
#### 1. Installation
MariaDB is the default implementation of MySQL in Arch Linux, provided with the mariadb package.

**Install mariadb**, and run the following command **before starting** the ```mariadb.service```
```bash
# mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
```

#### 2. Configuration
Once you have started the MariaDB server and added a root account, you may want to change the default configuration.

To log in as root on the MariaDB server, use the following command:
```bash
# mariadb -u root -p
```
##### 2.1 Add user
Creating a new user takes two steps: ```create the user```; ```grant privileges```. In the below example, the user monty with some_pass as password is being created, then granted full permissions to the database mydb:

```bash
# mariadb -u root -p
```
```mysql
MariaDB> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
MariaDB> GRANT ALL PRIVILEGES ON mydb.* TO 'monty'@'localhost';
MariaDB> quit
```

### 安装 PyMySQL 和 Flask-SQLAlchemy
使用python 提供 ```pip``` 包管理器安装 ```pymysql``` 和 ```Flask-SQLAlchemy```
```bash
$ pip install PyMySQL
$ pip install flask-sqlalchemy
```
#### Connection URI Format
For a complete list of connection URIs head over to the SQLAlchemy documentation under (Supported Databases). This here shows some common connection strings.

SQLAlchemy indicates the source of an Engine as a URI combined with optional keyword arguments to specify options for the Engine. The form of the URI is:
```python
dialect+driver://username:password@host:port/database
```

MySQL:
```python
mysql://scott:tiger@localhost/mydatabase
```

### Configuration Keys
**SQLALCHEMY_DATABASE_URI**

The database URI that should be used for the connection. Examples:
- sqlite:////tmp/test.db
- mysql://username:password@server/db

### 创建数据库
安装完上边的套件后，就可以正式创建Mysql数据库了。
#### 使用root用户创建数据库
```bash
sudo mariadb -u root -p
```
进入mariadb后，使用如下命令创建数据库：
```sql
MariaDB [(none)]> create database proj_20230325;
Query OK, 1 row affected (0.000 sec)
```

#### 给予权限
之后给予用户 Yarnom 该数据库的所有权限：
```sql
MariaDB [(none)]> GRANT ALL PRIVILEGES ON proj_20230325.* TO 'yarnom'@'localhost';
Query OK, 0 rows affected (0.009 sec)
```
### 安装 FLask-Migrate
```bash
$ pip install Flask-Migrate
```
#### 配置
```python
from flask_migrate import Migrate
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://yarnom:root@localhost:3306/proj_20230325"
db = SQLAlchemy(app)
Migrate(app,db)
```

#### 初始化
```bash
$ flask db init
```

### Flask 使用Mysql数据库
创建出相应的模板：

```python
class Student(db.Model):
    id = db.Column('id', db.String(100),primary_key=True)
    name = db.Column('name',db.String(100))
    def __init__(self, id, name):
        self.id =id
        self.name = name
```

使用如下命令更新数据库
```bash
$ flask db migrate -m "說明文字"
$ flask db upgrade
```
### Flask-Sqlalchemy 使用
> 以下内容转载自[flask-sqlalchemy 官方文档](https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/)
#### Flask 添加数据
```python
me = User('admin', 'admin@example.com')
db.session.add(me)
db.session.commit()
```
#### Flask 查询数据
So how do we get data back out of our database? For this purpose Flask-SQLAlchemy provides a query attribute on your Model class. When you access it you will get back a new query object over all records. You can then use methods like filter() to filter the records before you fire the select with all() or first(). If you want to go by primary key you can also use get().

The following queries assume following entries in the database:
|id|username|email|
|---|---|---|
|1|admin|admin@example.com|
|2|peter|peter@example.org|
|3|guest|guest@example.com|

Retrieve a user by username:
```bash
>>> peter = User.query.filter_by(username='peter').first()
>>> peter.id
2
>>> peter.email
u'peter@example.org'
```

Same as above but for a non existing username gives None:
```bash
>>> missing = User.query.filter_by(username='missing').first()
>>> missing is None
True
```

Selecting a bunch of users by a more complex expression:
```bash
>>> User.query.filter(User.email.endswith('@example.com')).all()
[<User u'admin'>, <User u'guest'>]
```

Ordering users by something:
```bash
>>> User.query.order_by(User.username).all()
[<User u'admin'>, <User u'guest'>, <User u'peter'>]
```

Limiting users:
```bash
>>> User.query.limit(1).all()
[<User u'admin'>]
```
Getting user by primary key:
```bash
>>> User.query.get(1)
<User u'admin'>
```
