Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to MSSQL in Flask using Flask-SQLAlchemy and pyodbc

I am not able to connect to MSSQL Server 2016 database using Flask-SQLALchemy and pyodbc. I have searched through Google and none of the solutions work.

I am getting the following error:

sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002', u'[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)')

My current local environment is:

  • Windows 7 Professional
  • Python 2.7

I am able to connect to the database with just pyodbc and no 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()

Application Code Snippets

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
like image 294
Kumaran S Avatar asked Nov 07 '22 06:11

Kumaran S


1 Answers

This should work as your SQLALCHEMY_DATABASE_URI connection value:

mssql://user:pwd!@PATH_TO_MSSQL_LOCATION?driver=SQL+Server+Native+Client+11.0

You might need to experiment with different version numbers up and down, although the version of the native driver is probably ascertainable.

like image 153
CodeMantle Avatar answered Nov 14 '22 22:11

CodeMantle