使用python命令行参数以JSON格式从SQL Server数据库检索数据

时间:2019-12-03 06:05:15

标签: json sql-server python-3.x

我正在尝试将SQL Server数据库中的数据转换为JSON格式。使用命令行参数,在cmd中,我将url和id作为输入py filename.py "http://../url/endpoint" 1传递,并根据id检索数据并以JSON格式获取。

我在cmd中遇到错误:

print(jsonFile)
UnboundLocalError: local variable 'jsonFile' referenced before assignment 

这是我的代码:

def get_url():
    Token = get_token_id()
    url = sys.argv[1]
    Header = {"Content-Type": "application/json", 'Authorization': 'Bearer ' + str(Token)}
    request1 = sys.argv[2]

    #try:
    conn = pyodbc.connect('Driver={SQL Server};'
                              'Server=localhost;'
                              'Database=testdb;'
                              'Trusted_Connection=yes;')

    cursor = conn.cursor()
    qa = "select * from dbo.testdb where id = '" + request1 + "' FOR JSON PATH "
    jsonF = cursor.execute(qa).fetchall()

    for row in jsonF:
        jsonP = json.dumps(list(row))
        jsonFile = json.loads(jsonP)
    print(jsonFile)

    response = requests.request("POST", headers=Header, url=url, data=jsonFile)

    statusCode = response.status_code
    print(response.text)

get_endpoint()

有人可以纠正我我的代码在做什么错吗?

0 个答案:

没有答案