简体   繁体   English

使用 Flask-SQLAlchemy 连接到 MSSQL 数据库

[英]Connect to MSSQL Database using Flask-SQLAlchemy

I'm trying to connect to a local MSSQL DB through Flask-SQLAlchemy.我正在尝试通过 Flask-SQLAlchemy 连接到本地 MSSQL 数据库。

Here's a code excerpt from my __init__.py file:这是我的__init__.py文件的代码摘录:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pyodbc://HARRISONS-THINK/LendApp'
db = SQLAlchemy(app)

SQLALCHEMY_TRACK_MODIFICATIONS = False

As you can see in SQL Server Management Studio, this information seems to match:正如您在 SQL Server Management Studio 中看到的,此信息似乎匹配:

在此处输入图片说明

Here is the creation of a simple table in my models.py file:这是在我的models.py文件中创建一个简单的表:

from LendApp import db

class Transaction(db.model):
    transactionID = db.Column(db.Integer, primary_key=True)
    amount = db.Column(db.Integer)
    sender = db.Column(db.String(80))
    receiver = db.Column(db.String(80))

    def __repr__(self):
        return 'Transaction ID: {}'.format(self.transactionID)

I am then connecting to the database using a Python Console within Pycharm via the execution of these two lines:然后我通过执行以下两行使用 Pycharm 中的 Python 控制台连接到数据库:

>>> from LendApp import db
>>> db.create_all()

This is resulting in the following error:这导致以下错误:

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

The only thing that I can think of is that my database connection string is incorrect.我唯一能想到的是我的数据库连接字符串不正确。 I have tried altering it to more of a standard Pyodbc connection string and including driver={SQL SERVER} but to no prevail.我尝试将其更改为更多标准 Pyodbc 连接字符串并包括driver={SQL SERVER}但没有成功。

If anyone could help me out with this it would be highly appreciated.如果有人能帮我解决这个问题,我将不胜感激。

Thanks谢谢

So I just had a very similar problem and was able to solve by doing the following.所以我只是遇到了一个非常相似的问题,并且能够通过执行以下操作来解决。

Following the SQL Alchemy documentation I found I could use the my pyodbc connection string like this:按照SQL Alchemy 文档,我发现我可以像这样使用我的 pyodbc 连接字符串:

# Python 2.x
import urllib
params = urllib.quote_plus("DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password")
engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)

# Python 3.x
import urllib
params = urllib.parse.quote_plus("DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password")
engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)


# using the above logic I just did the following
params = urllib.parse.quote_plus('DRIVER={SQL Server};SERVER=HARRISONS-THINK;DATABASE=LendApp;Trusted_Connection=yes;')
app.config['SQLALCHEMY_DATABASE_URI'] = "mssql+pyodbc:///?odbc_connect=%s" % params

This then caused an additional error because I was also using Flask-Migrate and apparently it doesn't like % in the connection URI.然后这导致了一个额外的错误,因为我也在使用 Flask-Migrate 并且显然它不喜欢连接 URI 中的 % 。 So I did some more digging and found this post .所以我做了更多的挖掘并找到了这篇文章 I then changed the following line in my ./migrations/env.py file然后我在我的./migrations/env.py文件中更改了以下行

From:来自:

from flask import current_app
config.set_main_option('sqlalchemy.url',
                   current_app.config.get('SQLALCHEMY_DATABASE_URI'))

To:至:

from flask import current_app
db_url_escaped = current_app.config.get('SQLALCHEMY_DATABASE_URI').replace('%', '%%')
config.set_main_option('sqlalchemy.url', db_url_escaped)

After doing all this I was able to do my migrations and everything seems as if it is working correctly now.完成所有这些之后,我能够进行迁移,现在一切似乎都可以正常工作。

If someone still stumbled upon this issue and trying to figure out another solution then try with pymssql instead of pyodbc ;如果有人仍然偶然发现这个问题并试图找出另一个解决方案,那么尝试使用pymssql而不是pyodbc

pip install pymssql

Connection URI would be:连接 URI 将是:

conn_uri = "mssql+pymssql://<username>:<password>@<servername>/<dbname>"

I had the same problem, it was resolved by specifying:我有同样的问题,它是通过指定解决的:

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mssql+pyodbc://MySQLServerName/MyTestDb?driver=SQL+Server?trusted_connection=yes"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)

I believe your connection string is missing the authentication details.我相信您的连接字符串缺少身份验证详细信息。 From Flask-SQLAlchemy documentation, the connection string should have the following format从 Flask-SQLAlchemy 文档中,连接字符串应具有以下格式

dialect+driver://username:password@host:port/database

From your example, I believe it will look something like this从您的示例中,我相信它看起来像这样

app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pyodbc://<username>:<password>@<Host>:<Port>/LendApp'

I just changed my connection string something like this and its worked perfectly我只是改变了我的连接字符串这样的东西,它工作得很好

NOTE: you need to install pyodbc to work....注意:您需要安装 pyodbc 才能工作....

app.config["SQLALCHEMY_DATABASE_URI"] = "mssql+pyodbc://user:pwd@server/database?driver=SQL+Server"

using below solution i get resolve my connection issue with MSSQL server使用以下解决方案,我解决了与 MSSQL 服务器的连接问题

params = urllib.parse.quote_plus('DRIVER={SQL Server};SERVER=HARRISONS-THINK;DATABASE=LendApp;Trusted_Connection=yes;')
app.config['SQLALCHEMY_DATABASE_URI'] = "mssql+pyodbc:///?odbc_connect=%s" % params

If you are getting any Login failed for User error then please go to this http://itproguru.com/expert/2014/09/how-to-fix-login-failed-for-user-microsoft-sql-server-error-18456-step-by-step-add-sql-administrator-to-sql-management-studio/ .如果您因用户错误而遇到任何登录失败,请访问此http://itproguru.com/expert/2014/09/how-to-fix-login-failed-for-user-microsoft-sql-server-error -18456-step-by-step-add-sql-administrator-to-sql-management-studio/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM