correct syntax for SQL calls in python with pyodbc

Viewed 76

I need help to write the SQL calls from my python scripts in a proper way. what I my script currently looks like is :

import pyodbc
cnx = pyodbc.connect(**connection details**)
c = cnx.cursor()
results = c.execute("select * .....")
final_result= results.fetchall()

issue is sometimes result value is NONE type object and sometimes I get a return values.

I want to know if the below way is a correct way to call , because it seems to work everytime for all the queries

import pyodbc

cnx = pyodbc.connect(**connection details**)

c = cnx.cursor()

c.execute("select * .....")
final_result= c.fetchall()
1 Answers

Your second approach is correct and is what many DB API modules require. However, pyodbc has extended the DB API specification so that Cursor.execute() returns the Cursor object itself so you can simply do

final_result = c.execute("select * .....").fetchall()
Related