-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysql.py
32 lines (27 loc) · 1.06 KB
/
mysql.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
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import text
class MySQLConnection(object):
def __init__(self, app, db):
config = {
'host': 'localhost',
'database': db,
'user': 'root',
'password': 'root',
'port': '8889'
}
DATABASE_URI = "mysql://{}:{}@127.0.0.1:{}/{}".format(config['user'], config['password'], config['port'], config['database'])
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
self.db = SQLAlchemy(app)
def query_db(self, query, data=None):
result = self.db.session.execute(text(query), data)
if query[0:6].lower() == 'select':
list_result = [dict(r) for r in result]
return list_result
elif query[0:6].lower() == 'insert':
self.db.session.commit()
return result.lastrowid
else:
self.db.session.commit()
def MySQLConnector(app, db):
return MySQLConnection(app, db)