commit 8d45a2505b52b48c60142aecbfbbb6144fcea2ed Author: Bartal Laearsson Date: Wed Aug 26 21:08:20 2026 +0100 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0a764a4 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +env diff --git a/README.md b/README.md new file mode 100644 index 0000000..c5ff9a1 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +# README + +## requirements + +python 3.13 or something +mssql server +install pip install pyodbc + + + +check if odbc 17 (or other version) +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/advanced-topics/bulk_insert.py b/advanced-topics/bulk_insert.py new file mode 100644 index 0000000..310c467 --- /dev/null +++ b/advanced-topics/bulk_insert.py @@ -0,0 +1,42 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + cursor = connection.cursor() + + create_table=""" + IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbl_customers_from_csv_bulk_insert]') AND type in (N'U')) + begin + create table [dbo].[tbl_customers_from_csv_bulk_insert]( + id int not null, + code varchar(50) null, + first_name varchar(50) null, + last_name varchar(50) null, + ) + end; + """ + cursor.execute(create_table) + connection.commit() + + bulk_insert_cmd=""" + bulk insert tbl_customers_from_csv_bulk_insert + from 'C:\\Users\\bl.SEV\\repos\\python-mssql\\advanced-topics\\csv\\sample-csv-file-for-bulk-insert-demo.csv' + with + ( + fieldterminator = ';', + rowterminator = '\n' + ); + """ + cursor.execute(bulk_insert_cmd) + connection.commit() + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() diff --git a/advanced-topics/call_sql_scripts_via_ps.py b/advanced-topics/call_sql_scripts_via_ps.py new file mode 100644 index 0000000..98b3a58 --- /dev/null +++ b/advanced-topics/call_sql_scripts_via_ps.py @@ -0,0 +1,41 @@ +import subprocess +import os + +sql_instance = "." +sql_database = "master" +folder_to_check = "./sql_scripts/" + +def run_ps_command(cmd): + # Build the PowerShell invocation list + command = [ + "PowerShell", + "-ExecutionPolicy", "Unrestricted", + "-Command", cmd + ] + + result = subprocess.run( + command, + capture_output=True, + text=True + ) + return result + +for file in os.listdir(folder_to_check): + if file.endswith(".sql"): + full_path = os.path.join(folder_to_check, file) + print(f"executing .sql file: {full_path}") + + sql_command = ( + f"Invoke-Sqlcmd -ServerInstance {sql_instance} " + f"-Database {sql_database} -InputFile \"{full_path}\"" + ) + + result = run_ps_command(sql_command) + + if result.returncode != 0: + print("Error executing script:") + print(result.stderr.strip()) + else: + if result.stdout: + print("Output:") + print(result.stdout.strip()) diff --git a/advanced-topics/create_basic_tui.py b/advanced-topics/create_basic_tui.py new file mode 100644 index 0000000..c80f4c0 --- /dev/null +++ b/advanced-topics/create_basic_tui.py @@ -0,0 +1,45 @@ +import tkinter +import pyodbc + +sql_server_ver = "Not Available" + +root = tkinter.Tk() +root.geometry("600x400") +root.title("Sample Python GUI App") + +label_hello_world = tkinter.Label(root, text=str(sql_server_ver), fg="red") + +def sql_server_version(): + + 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 + sql_server_ver = row.version + + cursor.close() + connection.close() + + except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() + + label_hello_world.config(text=str(sql_server_ver)) + label_hello_world.pack() + +btn_sql_server_version = tkinter.Button(root, command=sql_server_version, text="Retrieve SQL Server Version") +btn_sql_server_version.pack(side=tkinter.TOP, pady=50) + + +root.mainloop() diff --git a/advanced-topics/csv/sample-csv-file-for-bulk-insert-demo.csv b/advanced-topics/csv/sample-csv-file-for-bulk-insert-demo.csv new file mode 100644 index 0000000..257b084 --- /dev/null +++ b/advanced-topics/csv/sample-csv-file-for-bulk-insert-demo.csv @@ -0,0 +1,5 @@ +1;customer1;fistName1;lastName1 +2;customer2;fistName2;lastName2 +3;customer3;fistName3;lastName3 +4;customer4;fistName4;lastName4 +5;customer5;fistName5;lastName5 diff --git a/advanced-topics/csv/sample-csv-file-for-demo.csv b/advanced-topics/csv/sample-csv-file-for-demo.csv new file mode 100644 index 0000000..257b084 --- /dev/null +++ b/advanced-topics/csv/sample-csv-file-for-demo.csv @@ -0,0 +1,5 @@ +1;customer1;fistName1;lastName1 +2;customer2;fistName2;lastName2 +3;customer3;fistName3;lastName3 +4;customer4;fistName4;lastName4 +5;customer5;fistName5;lastName5 diff --git a/advanced-topics/sql_scripts/sqlscript1.sql b/advanced-topics/sql_scripts/sqlscript1.sql new file mode 100644 index 0000000..f1078f5 --- /dev/null +++ b/advanced-topics/sql_scripts/sqlscript1.sql @@ -0,0 +1,10 @@ +create database SampleDB2022_1a; +go + +use SampleDB2022_1a; +go + +create table tblSample1a( +id int, +code varchar(50)); +go diff --git a/advanced-topics/sql_scripts/sqlscript2.sql b/advanced-topics/sql_scripts/sqlscript2.sql new file mode 100644 index 0000000..f595533 --- /dev/null +++ b/advanced-topics/sql_scripts/sqlscript2.sql @@ -0,0 +1,14 @@ +use SampleDB2022_1a; +go + +insert into tblSample1a +values (1,'test1'), (2,'test2'); + +create table tblSample1b( +id int, +code varchar(50)); +go + +insert into tblSample1b +values (1,'test1'), (2,'test2'); +go diff --git a/advanced-topics/sql_scripts/sqlscript3.sql b/advanced-topics/sql_scripts/sqlscript3.sql new file mode 100644 index 0000000..31d2bbe --- /dev/null +++ b/advanced-topics/sql_scripts/sqlscript3.sql @@ -0,0 +1,14 @@ +create database SampleDB2022_1b; +go + +use SampleDB2022_1b; +go + +create table tblSample1a( +id int, +code varchar(50)); + +create table tblSample1b( +id int, +code varchar(50)); +go diff --git a/advanced-topics/write_csv_sql_server.py b/advanced-topics/write_csv_sql_server.py new file mode 100644 index 0000000..7a678fe --- /dev/null +++ b/advanced-topics/write_csv_sql_server.py @@ -0,0 +1,71 @@ +import pyodbc +import csv + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + print("[creating table tbl_customers_from_csv...]") + create_table="""IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbl_customers_from_csv]') AND type in (N'U')) + begin + create table [dbo].[tbl_customers_from_csv] ( + id int not null, + code varchar(50) null, + first_name varchar(50) null, + last_name varchar(50) null, + ) + end; + """ + + cursor.execute(create_table) + connection.commit() + + print("[selecting from table before csv insert...]") + cursor.execute("select * from tbl_customers_from_csv") + while 1: + row = cursor.fetchone() + if not row: + break + print(row.id, row.code, row.first_name, row.last_name) + + print() + + # read csv file and insert each row into table in sql server + print("[reading csv file and insert new rows into sql server table...]") + with open("./csv/sample-csv-file-for-demo.csv", newline='') as csv_file: + csv_reader = csv.reader(csv_file, delimiter=';', quotechar='|') + for row in csv_reader: + prm_id=row[0] + prm_code=row[1] + prm_first_name=row[2] + prm_last_name=row[3] + + print("inserting record:",', '.join(row)) + cursor.execute("insert into dbo.tbl_customers_from_csv values (?,?,?,?)", prm_id, prm_code, prm_first_name, prm_last_name) + connection.commit() + + print() + + print("[select table after inserts...]") + cursor.execute("select * from tbl_customers_from_csv") + while 1: + row = cursor.fetchone() + if not row: + break + print(row.id, row.code, row.first_name, row.last_name) + + print() + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() + +print() diff --git a/basic-sql-server-interactions-and-dml/connect_sql_server_exception.py b/basic-sql-server-interactions-and-dml/connect_sql_server_exception.py new file mode 100644 index 0000000..8172ada --- /dev/null +++ b/basic-sql-server-interactions-and-dml/connect_sql_server_exception.py @@ -0,0 +1,22 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + print() + print("Successfully connected to SQL Server") + print() + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ", ex) + print("closing program") + print() + exit() + +print() diff --git a/basic-sql-server-interactions-and-dml/delete_no_param_tsql.py b/basic-sql-server-interactions-and-dml/delete_no_param_tsql.py new file mode 100644 index 0000000..b0f83ba --- /dev/null +++ b/basic-sql-server-interactions-and-dml/delete_no_param_tsql.py @@ -0,0 +1,43 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + print("select before deleteing...") + + cursor.execute("select * from tblCustomers") + + while 1: + row = cursor.fetchone() + if not row: + break + print(row.id, row.code, row.firstName, row.lastName) + + cursor.execute("delete from tblCustomers where id = 2") + connection.commit() + + print("select after deleting") + cursor.execute("select * from tblCustomers") + + 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() diff --git a/basic-sql-server-interactions-and-dml/delete_with_param_tsql.py b/basic-sql-server-interactions-and-dml/delete_with_param_tsql.py new file mode 100644 index 0000000..10269bd --- /dev/null +++ b/basic-sql-server-interactions-and-dml/delete_with_param_tsql.py @@ -0,0 +1,44 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + print("select before deleteing...") + + cursor.execute("select * from tblCustomers") + + while 1: + row = cursor.fetchone() + if not row: + break + print(row.id, row.code, row.firstName, row.lastName) + + prm_code = "code6" + cursor.execute("delete from tblCustomers where code = ?", prm_code) + connection.commit() + + print("select after deleting") + cursor.execute("select * from tblCustomers") + + 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() diff --git a/basic-sql-server-interactions-and-dml/insert_no_param_tsql.py b/basic-sql-server-interactions-and-dml/insert_no_param_tsql.py new file mode 100644 index 0000000..2baf8a3 --- /dev/null +++ b/basic-sql-server-interactions-and-dml/insert_no_param_tsql.py @@ -0,0 +1,45 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + print("") + print("select statement before insert") + cursor.execute("select * from tblCustomers") + + while 1: + row = cursor.fetchone() + if not row: + break + print(row.id, row.code, row.firstName, row.lastName) + + print("inserting into tblCustomers...") + cursor.execute("insert into tblCustomers values (6, 'code6', 'firstName6', 'lastName6')") + connection.commit() + + print("select statement after insert") + cursor.execute("select * from tblCustomers") + + 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() diff --git a/basic-sql-server-interactions-and-dml/insert_with_param_tsql.py b/basic-sql-server-interactions-and-dml/insert_with_param_tsql.py new file mode 100644 index 0000000..3ac16a1 --- /dev/null +++ b/basic-sql-server-interactions-and-dml/insert_with_param_tsql.py @@ -0,0 +1,46 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + print("") + print("select statement before insert") + cursor.execute("select * from tblCustomers") + + while 1: + row = cursor.fetchone() + if not row: + break + print(row.id, row.code, row.firstName, row.lastName) + + prm_id = 7 + prm_code = "code7" + prm_first_name = "firstName7" + prm_last_name = "lastName7" + print("inserting into tblCustomers...") + cursor.execute("insert into tblCustomers values (?, ?, ?, ?)", prm_id, prm_code, prm_first_name, prm_last_name) + connection.commit() + + print("select statement after insert") + cursor.execute("select * from tblCustomers") + + 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() diff --git a/basic-sql-server-interactions-and-dml/other_queries_tsql.py b/basic-sql-server-interactions-and-dml/other_queries_tsql.py new file mode 100644 index 0000000..a38fb55 --- /dev/null +++ b/basic-sql-server-interactions-and-dml/other_queries_tsql.py @@ -0,0 +1,58 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + + # wuery 1 + print("counting all records in table...") + cursor.execute("select count(*) as total_records from tblCustomers") + + + while 1: + row = cursor.fetchone() + if not row: + break + print(row.total_records) + print("--- next query ----") + + # query 2 + print("fetching server name...") + cursor.execute("select @@SERVERNAME as server_name") + + while 1: + row = cursor.fetchone() + if not row: + break + print(row.server_name) + print("--- next query ----") + + # query 3 + print("some DMV stuff...") + cursor.execute("select top 10 wait_type, wait_time_ms from sys.dm_os_wait_stats where wait_time_ms > 5 order by wait_time_ms desc") + + while 1: + row = cursor.fetchone() + if not row: + break + print(row.wait_type, row.wait_time_ms) + + print("--- no more queries ... ----") + + + + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() + +print() diff --git a/basic-sql-server-interactions-and-dml/running_simple_query.py b/basic-sql-server-interactions-and-dml/running_simple_query.py new file mode 100644 index 0000000..82a8b41 --- /dev/null +++ b/basic-sql-server-interactions-and-dml/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/basic-sql-server-interactions-and-dml/select_no_param_tsql.py b/basic-sql-server-interactions-and-dml/select_no_param_tsql.py new file mode 100644 index 0000000..9298670 --- /dev/null +++ b/basic-sql-server-interactions-and-dml/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() diff --git a/basic-sql-server-interactions-and-dml/select_param_tsql.py b/basic-sql-server-interactions-and-dml/select_param_tsql.py new file mode 100644 index 0000000..c929ce1 --- /dev/null +++ b/basic-sql-server-interactions-and-dml/select_param_tsql.py @@ -0,0 +1,35 @@ +import pyodbc + +try: + + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + prmID = 5 + + cursor.execute("select * from tblCustomers where id = ?",prmID) + + 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() + + + diff --git a/basic-sql-server-interactions-and-dml/update_no_param_tsql.py b/basic-sql-server-interactions-and-dml/update_no_param_tsql.py new file mode 100644 index 0000000..7b3d6a5 --- /dev/null +++ b/basic-sql-server-interactions-and-dml/update_no_param_tsql.py @@ -0,0 +1,39 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + print("select table before updating") + + cursor.execute("select * from tblCustomers") + while 1: + row = cursor.fetchone() + if not row: + break + print(row.id, row.code, row.firstName, row.lastName) + + cursor.execute("update tblCustomers set lastName = 'lastName New 5' where id = 5") + connection.commit() + + print("table after updating") + cursor.execute("select * from tblCustomers") + 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() diff --git a/basic-sql-server-interactions-and-dml/update_with_param_tsql.py b/basic-sql-server-interactions-and-dml/update_with_param_tsql.py new file mode 100644 index 0000000..33eadd3 --- /dev/null +++ b/basic-sql-server-interactions-and-dml/update_with_param_tsql.py @@ -0,0 +1,40 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + print("select table before updating") + + cursor.execute("select * from tblCustomers") + while 1: + row = cursor.fetchone() + if not row: + break + print(row.id, row.code, row.firstName, row.lastName) + + prm_id = 7 + cursor.execute("update tblCustomers set lastName = 'lastName New 7' where id = ?", prm_id) + connection.commit() + + print("table after updating") + cursor.execute("select * from tblCustomers") + 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() diff --git a/functions/call_func.py b/functions/call_func.py new file mode 100644 index 0000000..3a10de1 --- /dev/null +++ b/functions/call_func.py @@ -0,0 +1,37 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + + sql_cmd="select dbo.ufn_get_cus_code(?) as cus_code" + + prm_id=4 + + cursor.execute(sql_cmd,prm_id) + + print("using udf to retrieve cus code...") + + while 1: + row = cursor.fetchone() + if not row: + break + print("Customer code for id ", prm_id, " - ", row.cus_code) + + print() + + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() + +print() diff --git a/functions/call_sys_func.py b/functions/call_sys_func.py new file mode 100644 index 0000000..f585e3c --- /dev/null +++ b/functions/call_sys_func.py @@ -0,0 +1,54 @@ +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 HOST_NAME() as host_name") + + print("[system function 1 - host_name results...]") + while 1: + row = cursor.fetchone() + if not row: + break + print("host name:",row.host_name) + + print() + + cursor.execute("select DB_NAME() as current_db_name") + print("[system function 2 - current database results...]") + + while 1: + row = cursor.fetchone() + if not row: + break + print("current database name:", row.current_db_name) + + print() + + # sys func 3 + prm_is_numeric = "202424" + cursor.execute("select ISNUMERIC(?) as is_numeric_value", prm_is_numeric) + + print("[System function 3 - is numeric...]") + while 1: + row = cursor.fetchone() + if not row: + break + print("checking to see if param", prm_is_numeric, "is numeric. check resutl (0 / false, 1 / true):", row.is_numeric_value) + + print() + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() + +print() diff --git a/functions/create_function.py b/functions/create_function.py new file mode 100644 index 0000000..3c82053 --- /dev/null +++ b/functions/create_function.py @@ -0,0 +1,38 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + + sql_cmd="""create function ufn_get_cus_code (@cus_id int) + returns varchar(50) + as + begin + declare @cus_code varchar(50) + set @cus_code = (select code from tblCustomers where id = @cus_id) + + return @cus_code + + end; + """ + + cursor.execute(sql_cmd) + connection.commit() + + print("User defined function successfully created or altered...") + + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() + +print() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..41dc539 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +pyodbc +langchain +langchain-mcp-adapters +aiohttp diff --git a/stored-procedures/call_stored_procedure_with_no_results.py b/stored-procedures/call_stored_procedure_with_no_results.py new file mode 100644 index 0000000..2ef46d1 --- /dev/null +++ b/stored-procedures/call_stored_procedure_with_no_results.py @@ -0,0 +1,61 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + sql_cmd=""" + create or alter procedure usp_cus_details_update (@cus_id int) + as + update tblCustomers set lastName = lastName+' updated from sp' where id = @cus_id + """ + + cursor.execute(sql_cmd) + connection.commit + + print() + + print("[before sp update call...]") + cursor.execute("select * from tblCustomers") + + while 1: + row = cursor.fetchone() + if not row: + break + print(row.id, row.code, row.firstName, row.lastName) + + + + print() + + sql_cmd_2 =""" + exec usp_cus_details_update @cus_id = ?; + """ + + prm_id = 4 + + cursor.execute(sql_cmd_2, prm_id) + connection.commit + + print("[After sp update call...]") + cursor.execute("select * from tblCustomers") + + 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() diff --git a/stored-procedures/call_stored_procedure_with_results.py b/stored-procedures/call_stored_procedure_with_results.py new file mode 100644 index 0000000..a019bae --- /dev/null +++ b/stored-procedures/call_stored_procedure_with_results.py @@ -0,0 +1,40 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + sql_cmd = """ + declare @out nvarchar(max) + exec dbo.usp_cus_details @cus_id = ?, @out = @out output; + """ + + prm_id=3 + + cursor.execute(sql_cmd, prm_id) + + print("[printing sp call]") + rows = cursor.fetchall() + + while rows: + print(rows) + if cursor.nextset(): + rows = cursor.fetchall() + else: + rows = None + + print() + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() + +print() diff --git a/stored-procedures/create_stored_procedure.py b/stored-procedures/create_stored_procedure.py new file mode 100644 index 0000000..d159efc --- /dev/null +++ b/stored-procedures/create_stored_procedure.py @@ -0,0 +1,32 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + + sql_cmd=""" + create or alter procedure usp_cus_details (@cus_id int, @out nvarchar(max) output) + as + select * from tblCustomers where id = @cus_id + + """ + + cursor.execute(sql_cmd) + connection.commit() + + print("stored procedure successfully created or altered") + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() + +print() diff --git a/template b/template new file mode 100644 index 0000000..143bdf6 --- /dev/null +++ b/template @@ -0,0 +1,22 @@ +import pyodbc + +try: + connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') + + cursor = connection.cursor() + + + + + cursor.close() + connection.close() + +except pyodbc.Error as ex: + print() + print("exception: ",ex) + cursor.close() + connection.close() + print() + exit() + +print()