如何在django中运行普通SQL查询时获取字段名

mcvgt66p  于 2023-01-27  发布在  Go
关注(0)|答案(4)|浏览(159)

在我的一个django视图中,我使用plain sql(而不是orm)查询数据库并返回结果。

sql = "select * from foo_bar"
cursor = connection.cursor()
cursor.execute(sql)
rows = cursor.fetchall()

我可以很好地获取数据,但不能获取列名。如何获取返回的结果集的字段名?

7ivaypg9

7ivaypg91#

在Django文档中,提供了一个非常简单的方法(正如伊格纳西奥所回答的,它确实使用了cursor.description)。

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]
oknwwptz

oknwwptz2#

根据PEP 249,您可以尝试使用cursor.description,但这并不完全可靠。

7ajki6be

7ajki6be3#

我在Doug Hellmann的博客中找到了一个很好的解决方案:
http://doughellmann.com/2007/12/30/using-raw-sql-in-django.html

from itertools import *
from django.db import connection

def query_to_dicts(query_string, *query_args):
    """Run a simple query and produce a generator
    that returns the results as a bunch of dictionaries
    with keys for the column values selected.
    """
    cursor = connection.cursor()
    cursor.execute(query_string, query_args)
    col_names = [desc[0] for desc in cursor.description]
    while True:
        row = cursor.fetchone()
        if row is None:
            break
        row_dict = dict(izip(col_names, row))
        yield row_dict
    return

示例用法:

row_dicts = query_to_dicts("""select * from table""")
irlmq6kh

irlmq6kh4#

请尝试以下代码:

def read_data(db_name,tbl_name): 
    details = sfconfig_1.dbdetails
    connect_string = 'DRIVER=ODBC Driver 17 for SQL Server;SERVER={server}; DATABASE={database};UID={username}\
        ;PWD={password};Encrypt=YES;TrustServerCertificate=YES'.format(**details)

    connection = pyodbc.connect(connect_string)#connecting to the server
    print("connencted to db")
    # query syntax 

    query = 'select top 100 * from '+'[{}].[dbo].[{}]'.format(db_name,tbl_name) + ' t where t.chargeid ='+ "'622102*3'"+';'
    #print(query,"\n")
    df    = pd.read_sql_query(query,con=connection)
    print(df.iloc[0])

    return "connected to db...................."

相关问题