我正在尝试从sql视图中读取一些数据。我是pyodbc的驱动程序,我发现pyodbc无法读取视图。有没有一种方法可以在python函数中读取sql视图?
下面是一段示例代码:
import logging
import json
import pyodbc
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
server = '***.database.windows.net'
database = '**'
username = '**'
password = '**'
driver = '{SQL Server Native Client 11.0}'
cnxn = pyodbc.connect('DRIVER='+driver+';PORT=1433;SERVER='+server +
';PORT=1443;DATABASE='+database+';UID='+username+';PWD=' + password)
if req.method == 'GET':
result = []
logging.info('Python HTTP trigger function processed a request.')
name = req.params.get('name')
if not terminal_name:
try:
req_body = req.get_json()
except ValueError:
return func.HttpResponse(
"Invalid input Json response",
status_code=401
)
else:
name = req_body.get('name')
id = req_body.get('id')
query = f"""
Select distinct([product_type]), product_grade from cns_terminal_cockpit.v_terminal_outage
where terminal_id ={id} and lower(name) = '{name}'
and product_grade <> ''
"""
cursor = cnxn.cursor()
try:
cursor.execute(query)
except TypeError:
return func.HttpResponse(
'Failed. The issue is with the query',
status_code=402
)
for row in cursor.fetchall():
result.append(
dict(zip([column[0] for column in cursor.description], row))
)
del cnxn
return func.HttpResponse(
json.dumps(result, default=str),
mimetype="application/json",
status_code=200
)
else:
return func.HttpResponse(
'Wrong request method was posted, please use GET method',
status_code=403
)
我输出的json是[],status_code=200。但在后台,我在视图中有一些数据。当我查询一个普通的数据库表时,同样的代码工作就像一个魅力。
我研究过其他库,比如pymysql、jdbc。但似乎没有一个像预期的那样起作用。
我不确定你在哪里读到的,但应该直接从视图中读取数据:
import pyodbc
conn = pyodbc.connect ('CONNECTION_STRING')
cursor=conn.cursor()
cursor.execute('SELECT * FROM VIEW')
for row in cursor:
print(row)
它起作用了,问题是我的驱动程序过时了。我将SQL驱动程序更新为17。然后我可以连接到我的sql视图