select no param
This commit is contained in:
@@ -13,3 +13,13 @@ on windows search for odbc data sources.
|
|||||||
go to the menu point drivers.
|
go to the menu point drivers.
|
||||||
There should odbc driver 17 for mssql server or something like that
|
There should odbc driver 17 for mssql server or something like that
|
||||||
|
|
||||||
|
## common pitfalls
|
||||||
|
always close connections
|
||||||
|
use with statement (preferred) or try -> finally
|
||||||
|
sql injections
|
||||||
|
use parameterized queries
|
||||||
|
poor exception handling
|
||||||
|
log errors, use finally blocks, use tx, use AD
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import pyodbc
|
||||||
|
|
||||||
|
print()
|
||||||
|
|
||||||
|
try:
|
||||||
|
connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes')
|
||||||
|
|
||||||
|
cursor = connection.cursor()
|
||||||
|
|
||||||
|
cursor.execute("select @@version as version")
|
||||||
|
|
||||||
|
while 1:
|
||||||
|
row = cursor.fetchone()
|
||||||
|
if not row:
|
||||||
|
break
|
||||||
|
print(row.version)
|
||||||
|
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
except pyodbc.Error as ex:
|
||||||
|
print()
|
||||||
|
print("exception: ",ex)
|
||||||
|
print("closing program")
|
||||||
|
print()
|
||||||
|
exit()
|
||||||
|
|
||||||
|
print()
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import pyodbc
|
||||||
|
|
||||||
|
try:
|
||||||
|
connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes')
|
||||||
|
|
||||||
|
cursor = connection.cursor()
|
||||||
|
|
||||||
|
cursor.execute("select * from tblCustomers")
|
||||||
|
|
||||||
|
print("[query results...]")
|
||||||
|
while 1:
|
||||||
|
row = cursor.fetchone()
|
||||||
|
if not row:
|
||||||
|
break
|
||||||
|
print(row.id, row.code, row.firstName, row.lastName)
|
||||||
|
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
except pyodbc.Error as ex:
|
||||||
|
print()
|
||||||
|
print("exception: ",ex)
|
||||||
|
cursor.close()
|
||||||
|
connection.close()
|
||||||
|
print()
|
||||||
|
exit()
|
||||||
|
|
||||||
|
print()
|
||||||
Reference in New Issue
Block a user