title: Connecting to MSSQL in Flask using Flask-SQLAlchemy and pyodbc
body: <p>I am not able to connect to <strong>MSSQL Server 2016</strong> database using <code>Flask-SQLALchemy</code> and <code>pyodbc</code>. I have searched through Google and none of the solutions work.</p>
  
  <p>I am getting the following error:</p>
  
  <blockquote>
    <p>sqlalchemy.exc.InterfaceError: (pyodbc.InterfaceError) ('IM002',
    u'[IM002] [Microsoft][ODBC Driver Manager] Data source name not found
    and no default driver specified (0) (SQLDriverConnect)')</p>
  </blockquote>
  
  <p>My current local environment is:</p>
  
  <ul>
  <li>Windows 7 Professional</li>
  <li>Python 2.7</li>
  </ul>
  
  <p>I am able to connect to the database with just pyodbc and no Flask.</p>
  
  <pre><code>import pyodbc
  server = '&lt;server&gt;'
  database = '&lt;database&gt;'
  username = '&lt;username&gt;'
  password = '&lt;password&gt;'
  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()
  </code></pre>
  
  <p>Application Code Snippets</p>
  
  <p><strong>config.py</strong></p>
  
  <pre><code>SQLALCHEMY_DATABASE_URI = mssql+pyodbc:///?odbc_connect="DRIVER={ODBC Driver 13 for SQL Server};SERVER=&lt;server&gt;;DATABASE=&lt;database&gt;;UID=&lt;username&gt;;PWD=&lt;password&gt;
  SQLALCHEMY_TRACK_MODIFICATIONS = False
  </code></pre>
  
  <p><strong>__init__.py</strong></p>
  
  <pre><code>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
  </code></pre>