在Django中运行纯SQL查询时如何获取字段名称

问题描述 投票:9回答:4

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

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

我得到的数据很好,但是列名却没有。如何获取返回的结果集的字段名称?

python django
4个回答
10
投票

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


9
投票

[在Django docs上,提供了一个非常简单的方法(确实使用cursor.description,正如Ignacio回答)。

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

5
投票

我在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""") 

0
投票

尝试以下代码:def read_data(db_name,tbl_name):详细信息= sfconfig_1.dbdetailsconnect_string ='DRIVER =用于SQL Server的ODBC驱动程序17; SERVER = {服务器}; DATABASE = {数据库}; UID = {用户名} \; PWD = {密码};加密=是; TrustServerCertificate =是'.format(**详细信息)

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...................."
© www.soinside.com 2019 - 2024. All rights reserved.