Visual Studio 2013進行Python開發(二)---python鏈接sql server數據庫

1.首先須要安裝如下三個包:sql

sqlalchemy數據庫

flask-sqlalchemyjson

pydocflask

安裝方法以下:bootstrap

選擇env右鍵選擇「Install Python Package...」api

彈出以下界面,而後輸入包名點擊肯定便可服務器

 

 

2.在項目中添加一個「db_mg.py」的文件,代碼以下:session

#db_mg.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from FlaskWebProject3.models import Base
 
class DatabaseManagement():
    def __init__(self):
        self.engine = create_engine("mssql+pymssql://sa:123456@127.0.0.1/UserRights?charset=utf8",echo=True,encoding='utf-8',convert_unicode=True)

        DBsession = sessionmaker(bind=self.engine)    #建立DBsession類
        self.session = DBsession()    #建立對象
 
    def add_obj(self,obj):    #添加內容
        self.session.add(obj)
        self.session.commit()    #提交
        return obj
    def queryall(self,target_class):    #查詢內容
        result_list = self.session.query(target_class).all()
        return result_list
    def query_all(self,target_class,query_filter):    #查詢內容
        result_list = self.session.query(target_class).filter(query_filter).all()
        return result_list
 
    def update_by_filter(self, obj, update_hash,query_filter):     #更新內容
        self.session.query(obj.__class__).filter(query_filter).update(update_hash)
        self.session.commit()
 
    def delete_by_filter(self, obj, query_filter):     #刪除內容
        self.session.query(obj).filter(query_filter).delete()
 
    def close(self):    #關閉session
        self.session.close()
 
    def execute_sql(self, sql_str):    #執行sql語句
        return self.session.execute(sql_str)

其中app

create_engine("mssql+pymssql://sa:123456@127.0.0.1/User?charset=utf8",echo=True,encoding='utf-8',convert_unicode=True)中的"sa"爲帳戶登陸名,"123456" 爲數據庫登錄名,"127.0.0.1"爲登錄的數據庫的服務器名,"User"爲數據庫名,
若是不添加以下「charset=utf8」,有可能從數據庫中查詢出來的中文爲亂碼

 3.具體的調用以下:dom

views.py

"""
Routes and views for the flask application.
"""

from datetime import datetime
from flask import render_template, session
#from FlaskWebProject3 import app
from flask import Flask,request 
from flask.json import jsonify
import os
from flask.helpers import make_response

from flask_bootstrap import Bootstrap

from wtforms import StringField, SubmitField
from wtforms.validators import Required
from flask_wtf.form import Form
from sqlalchemy.sql.schema import Column
from sqlalchemy.ext.declarative.api import declarative_base
from click import INT
from lib2to3.fixer_util import String
from FlaskWebProject3 import app, models
from flask_sqlalchemy import SQLAlchemy
from FlaskWebProject3.models import Person, User, engine
from FlaskWebProject3.db_mg import DatabaseManagement
from sqlalchemy.orm.session import sessionmaker
from sqlalchemy.engine import create_engine
from _operator import and_

#from FlaskWebProject3.Person import Person




#app.config['SESSION_TYPE'] = 'filesystem'
#app.config['SECRET_KEY'] = os.urandom(24)
#app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pymssql://sa:123456@127.0.0.1/UserRights?charset=utf8'
#app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
##app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
#app.config['SQLALCHEMY_NATIVE_UNICODE']=True;
#app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True
#app.config['SQLALCHEMY_ECHO']=True
app.config['JSON_AS_ASCII']=False


@app.route('/111', methods=['GET'])
def GetUser():

 db_session=DatabaseManagement()
 query_filter=and_(Person.Name=="james",Person.Password=="123456");
 person_list = db_session.queryall(Person)
 output = {} 
 for item in person_list:
    output["Name"] = item.Name  
    output["Password"] = item.Password
    
 return jsonify({'message': output})   


if __name__ == '__main__':
 

 app.run(self)
   

注意

app.config['JSON_AS_ASCII']=False是設置返回的json對象中中文是否亂碼,若是不設置則json中返回的中文爲亂碼
相關文章
相關標籤/搜索