学习烧瓶,无法连接到SQL Server

时间:2019-04-24 09:55:51

标签: sql-server flask get

我最近开始学习Flask。我正在尝试连接到本地SQL Server数据库并显示一个表。我不确定我是否正确地执行了连接字符串。

我不确定服务器的密码是什么。在SQL Server Management Studio中与Windows身份验证连接。我是否需要本地数据库的连接字符串?

我不确定该怎么做。我已经为此工作了好几个小时,但实际上我什么都没得到。 pyodbc.connect在pyCharm中连接,但未在浏览器中连接。无论如何尝试,我都会收到错误消息“服务器遇到内部错误,无法完成您的请求。服务器超载或应用程序中有错误。”

from flask import Flask, g, render_template, abort, request
import json
import pypyodbc as pyodbc

##cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
##                     "Server=LAPTOP-16DOMG6S\MSSQLSERVER3;"
  ##                    "Database=ImportTest;"
    ##                 "Trusted_Connection=yes;")

CONNECTION_STRING = 'Driver={ODBC Driver 17 for SQL Server};Server=LAPTOP->16DOMG6S\MSSQLSERVER3;' \
                   'Database=ImportTest;' \
                    'Uid = LAPTOP-16DOMG6S\dmc03' \
                    'Trusted_Connection=yes;'

app = Flask(__name__)
app.config.from_object(__name__)

##Displays the database table in pycharm with pyodbc.connect
##for row in cursor:
 ##  print('row = %r' % (row,))


@app.before_request
def before_request():
    try:
        g.sql_conn = pyodbc.connect(CONNECTION_STRING, autocommit=True)
    except Exception:
        abort(500, "No database connection could be established.")

@app.teardown_request
def teardown_request(exception):
    try:
        g.sql_conn.close()
    except AttributeError:
        pass





##Landing Page. Connection Working?

@app.route('/', methods=['GET'])
def hello():
    return 'This will display article information '



##Display All Articles in Database

@app.route('/articles', methods=['GET'])
def allArticle():
    curs = g.sql_conn.cursor()
    query = 'select * from ImportTest.dbo.gwTable2 '
    curs.execute(query)

    columns = [column[0] for column in curs.description]
    data = []

    for row in curs.fetchall():
        data.append(dict(zip(columns, row)))
   return json.dumps(data, indent=4, sort_keys=True, default=str)


if __name__ == '__main__':
   app.run()

我们将不胜感激

谢谢!

1 个答案:

答案 0 :(得分:0)

我注意到在CONNECTION_STRING变量上方的注释中,您将服务器命名为LAPTOP-16DOMG6S\MSSQLSERVER3,但在变量中还有一个额外的>

# Original
LAPTOP-16DOMG6S\MSSQLSERVER3\

# Variable
LAPTOP->16DOMG6S\MSSQLSERVER3
       ^
       | Notice the right arrow