15👍
✅
According to PEP 249, you can try using cursor.description
, but this is not entirely reliable.
26👍
On the Django docs, there’s a pretty simple method provided (which does indeed use cursor.description
, as Ignacio answered).
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()
]
- Django: IntegrityError during Many To Many add()
- What is the right way to use angular2 http requests with Django CSRF protection?
- Git push heroku master: Heroku push rejected, no Cedar-supported app detected
- Django Rest Framework debug post and put requests
7👍
I have found a nice solution in Doug Hellmann’s blog:
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
Example usage:
row_dicts = query_to_dicts("""select * from table""")
- How do you divide your project into applications in Django?
- What is the IP address of my heroku application
- How do I get the django HttpRequest from a django rest framework Request?
-1👍
try the following code :
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...................."
- FileField Size and Name in Template
- Does anyone know about workflow frameworks/libraries in Python?
- How to add some extra fields to the page in django-cms? (in django admin panel)
- Moving from direct_to_template to new TemplateView in Django
Source:stackexchange.com