1 from flask import Flask,jsonify,request 2 import json 3 from flask_cors import * 4 import pymysql 5 6 app = Flask(__name__) 7 8 import contextlib 9 10 @contextlib.contextmanager 11 12 def mysql(host='192.168.0.122', port=3306, user='root', passwd='我的数据库密码', db='text1',charset='utf8'): 13 conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset) 14 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 15 try: 16 yield cursor 17 finally: 18 conn.commit() 19 cursor.close() 20 conn.close() 21 22 @app.route('/aaa', methods=['GET','POST']) 23 @cross_origin() 24 def aaa(): 25 data= request.args.get("data")#获取前台json数据 26 temp = json.loads(data)#将json转为字典 27 id=temp['id']#获取相应的值 28 with mysql() as cursor: 29 print(cursor) 30 row_count = cursor.execute("select * from users where id=%s", (id)) 31 row_1 = cursor.fetchone() 32 return "successCallback"+"("+json.dumps(row_1)+")" 33 34 conn.commit() 35 cursor.close() 36 conn.close() 37 38 if __name__ == "__main__": 39 app.run( 40 host = '0.0.0.0', 41 port = 7777, 42 debug = True 43 )
from sqlalchemy import create_engine,text from sqlalchemy.orm import sessionmaker #定义数据库属性 hostname = '127.0.0.1' port = '3306' database = 'dbname' username = 'root' pwd = 'pwd' dburl = 'mysql + mysqldb://{}:{}@{}:{}/{}'.format(username,pwd,hostname,port,database) #创建数据库连接对象 engine = create_engine(dburl,echo=True) Session = sessionmaker(bind=engine) session = Session() session.execute('insert test values ('abc','123')') session.commmit() session.close()