0%

Flask连接MySQL数据库

在flask所在文件夹中新建一个models.py文件,输入以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import pymysql

def get_conn():
host = "127.0.0.1"
port = 3306 #注:此处应该使用数字而不是字符串
db = 'learn_flask_mysql'
user = 'root'
password = ''
conn = pymysql.connect(
host=host,
user=user,
password=password,
port=port,
db=db,
)
return conn

class User(object):
def __init__(self,user_id,user_name):
self.user_id = user_id
self.user_name = user_name

def save(self):
conn = get_conn()
cursor = conn.cursor()
sql = "INSERT INTO user(user_id, user_name) VALUES (%s,%s)"
cursor.execute(sql,(self.user_id,self.user_name))
conn.commit()
cursor.close()
conn.close()

@staticmethod
def query_all():
conn = get_conn()
cursor = conn.cursor()
sql = "SELECT * from user"
cursor.execute(sql)
rows = cursor.fetchall()
users = []
for row in rows:
user = User(row[0],row[1])
users.append(user)
conn.commit()
cursor.close()
conn.close()
return users

def __str__(self):
return "id:{} name:{}".format(self.user_id,self.user_name)

2.在flask新建文件夹中新建一个manage.py,并输入以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from flask_script import Manager
from learn_flask_mysql import app
from models import User

manager = Manager(app)

@manager.command
def save():
user = User(1,'csdn')
user.save()

@manager.command
def query_all():
users = User.query_all()
for user in users:
print(user)


if __name__ == "__main__":
manager.run()

之后使用python manage.py save即可保存数据,使用python manage.py qurey_all即可查询数据