我无法使用Flask-SQLAlchemy和pyodbc连接MSSQL Server 2016数据库。我已经通过Google搜索,但没有任何解决方案有效。我得到以下错误:
sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002', u'[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
我当前的本地环境是:
Windows 7 Professional Python 2.7
我可以只用pyodbc而没有Flask来连接到数据库。
sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002', u'[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')
我当前的本地环境是:
Windows 7 Professional Python 2.7
我可以只用pyodbc而没有Flask来连接到数据库。
import pyodbc
server = '<server>'
database = '<database>'
username = '<username>'
password = '<password>'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
#Select Query
print ('Reading data from table')
tsql = "SELECT DISTINCT TOP 10 * FROM dbo.Test;"
with cursor.execute(tsql):
row = cursor.fetchone()
while row:
print (str(row[0]) + " " + str(row[1]))
row = cursor.fetchone()
应用程序代码片段
config.py
SQLALCHEMY_DATABASE_URI = mssql+pyodbc:///?odbc_connect="DRIVER={ODBC Driver 13 for SQL Server};SERVER=<server>;DATABASE=<database>;UID=<username>;PWD=<password>
SQLALCHEMY_TRACK_MODIFICATIONS = False
__init__.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from config import Config
db = SQLAlchemy()
migrate = Migrate()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
migrate.init_app(app, db)
from app.errors import bp as errors_bp
app.register_blueprint(errors_bp)
from app.main import bp as main_bp
app.register_blueprint(main_bp)
return app
from app import models