diff --git a/README.md b/README.md index 2eafcb3..c5ff9a1 100644 --- a/README.md +++ b/README.md @@ -13,3 +13,13 @@ on windows search for odbc data sources. go to the menu point drivers. 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 + + + diff --git a/running_simple_query.py b/running_simple_query.py new file mode 100644 index 0000000..82a8b41 --- /dev/null +++ b/running_simple_query.py @@ -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() diff --git a/select_no_param_tsql.py b/select_no_param_tsql.py new file mode 100644 index 0000000..9298670 --- /dev/null +++ b/select_no_param_tsql.py @@ -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()