From c0237a4314ad371bdfab7d84d691a053db7f2c9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartal=20L=C3=A6arsson?= Date: Tue, 17 Feb 2026 13:39:00 +0000 Subject: [PATCH] kind of done. there is a mssql ML session, but not relevant right now --- advanced-topics/bulk_insert.py | 42 +++++++++ advanced-topics/call_sql_scripts_via_ps.py | 41 +++++++++ advanced-topics/create_basic_tui.py | 58 +++++++++---- .../sample-csv-file-for-bulk-insert-demo.csv | 5 ++ advanced-topics/sql_scripts/sqlscript1.sql | 23 +++++ advanced-topics/sql_scripts/sqlscript2.sql | 27 ++++++ advanced-topics/sql_scripts/sqlscript3.sql | 27 ++++++ requirements.txt | 3 + useful-sql-scripts/useful.sql | 87 +++++++++++++++++++ 9 files changed, 295 insertions(+), 18 deletions(-) create mode 100644 advanced-topics/bulk_insert.py create mode 100644 advanced-topics/call_sql_scripts_via_ps.py create mode 100644 advanced-topics/csv/sample-csv-file-for-bulk-insert-demo.csv create mode 100644 advanced-topics/sql_scripts/sqlscript1.sql create mode 100644 advanced-topics/sql_scripts/sqlscript2.sql create mode 100644 advanced-topics/sql_scripts/sqlscript3.sql create mode 100644 useful-sql-scripts/useful.sql 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 index 151ae49..c80f4c0 100644 --- a/advanced-topics/create_basic_tui.py +++ b/advanced-topics/create_basic_tui.py @@ -1,23 +1,45 @@ +import tkinter import pyodbc -import csv -try: - connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=.;DATABASE=SampleDB;Trusted_Connection=yes') +sql_server_ver = "Not Available" - cursor = connection.cursor() +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) - - - cursor.close() - connection.close() - -except pyodbc.Error as ex: - print() - print("exception: ",ex) - cursor.close() - connection.close() - print() - exit() - -print() +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/sql_scripts/sqlscript1.sql b/advanced-topics/sql_scripts/sqlscript1.sql new file mode 100644 index 0000000..7cae43d --- /dev/null +++ b/advanced-topics/sql_scripts/sqlscript1.sql @@ -0,0 +1,23 @@ +/* + * Created for the online course on Udemy: "Working with Python® on Windows® and SQL Server® Databases" + * + * Course URL: + * https://www.udemy.com/course/python-windows-sql-server + * + * Author/Instructor: Artemakis Artemiou + * + * Disclaimer: This SQL script which is part of the online course on Udemy "Working with Python® on Windows® + * and SQL Server® Databasess", is intended to be used only for demo purposes. Do not + * use it for Production systems as it is simplified for demo purposes. + */ + +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..84332c8 --- /dev/null +++ b/advanced-topics/sql_scripts/sqlscript2.sql @@ -0,0 +1,27 @@ +/* + * Created for the online course on Udemy: "Working with Python® on Windows® and SQL Server® Databases" + * + * Course URL: + * https://www.udemy.com/course/python-windows-sql-server + * + * Author/Instructor: Artemakis Artemiou + * + * Disclaimer: This SQL script which is part of the online course on Udemy "Working with Python® on Windows® + * and SQL Server® Databasess", is intended to be used only for demo purposes. Do not + * use it for Production systems as it is simplified for demo purposes. + */ + +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..450244c --- /dev/null +++ b/advanced-topics/sql_scripts/sqlscript3.sql @@ -0,0 +1,27 @@ +/* + * Created for the online course on Udemy: "Working with Python® on Windows® and SQL Server® Databases" + * + * Course URL: + * https://www.udemy.com/course/python-windows-sql-server + * + * Author/Instructor: Artemakis Artemiou + * + * Disclaimer: This SQL script which is part of the online course on Udemy "Working with Python® on Windows® + * and SQL Server® Databasess", is intended to be used only for demo purposes. Do not + * use it for Production systems as it is simplified for demo purposes. + */ + +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/requirements.txt b/requirements.txt index 57d5c35..41dc539 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,4 @@ pyodbc +langchain +langchain-mcp-adapters +aiohttp diff --git a/useful-sql-scripts/useful.sql b/useful-sql-scripts/useful.sql new file mode 100644 index 0000000..1da9f25 --- /dev/null +++ b/useful-sql-scripts/useful.sql @@ -0,0 +1,87 @@ +------------------------------------------------------ +-- 1. Solutions to common issues +------------------------------------------------------ +-- Resolving the "Divide by zero" error (by example) +DECLARE @denominator INT +SET @denominator = 0 +--SELECT 1 / 0 +SELECT 1 / ISNULL(NULLIF(@denominator, 0), 1) +------------------------------------------------------ +--Handling the error “The conversion of a char data type to a datetime data +--type resulted in an out-of-range datetime value” +--Change the default language to “us_english” for the given SQL Server login: +USE [master]; +ALTER LOGIN "LOGIN_NAME" WITH DEFAULT_LANGUAGE = us_english; +--Best practice: Always use the ISO date format in your data applications/T-SQL scripts: YYYY-MM-DD +------------------------------------------------------ +--Handling the error “Database [Database_Name] cannot be upgraded because it is read-only +--or has read-only files” +--Make sure that the user account on which the SQL Server instance database engine is +--running has full access to the database files. +------------------------------------------------------ +-- 2. Basic String Functions +------------------------------------------------------ +-- Returns @length characters from @expression starting from @start_index +SELECT SUBSTRING(@expression, @start_index, @length) +SELECT SUBSTRING('This is a Test', 1, 4) +-- Finds the given @pattern in the @string and replaces it with the @replacement_string +SELECT REPLACE(@string, @pattern, @replacement_string) +SELECT REPLACE('This is a Test', 'Test', 'New Test') +-- Returns the size of @string in terms of number of characters +SELECT LEN(@string) +SELECT LEN('This is a Test') +-- Returns the first @num_chars characters of the @string counting from the left +SELECT LEFT(@string, @num_chars) +SELECT LEFT('This is a Test',4) +-- Returns the first @num_chars characters of the @string counting from the right +SELECT RIGHT(@string, @num_chars) +SELECT RIGHT('This is a Test',4) +-- Removes the leading blank spaces +SELECT LTRIM(@expression) +SELECT LTRIM(' This is a Test') +-- Removes the trailing blank spaces +SELECT RTRIM(@expression) +SELECT RTRIM('This is a Test ') +------------------------------------------------------ +-- 3. Performance-Related Tips +------------------------------------------------------ +-- Avoiding locking when reading data (however, dirty reads are allowed) +-- You need to take into consideration, possible dirty-read issues when using this approach +SELECT [columnName] +FROM [tableName] WITH (NOLOCK) +------------------------------------------------------ +-- Rebuild a specific index with using parameters +USE [DATABASE_NAME]; +ALTER INDEX [INDEX_NAME] ON [SCHEMA.TABLE] +REBUILD WITH (FILLFACTOR=[FILL_FACTOR_VALUE_BETWEEN_0_100], ONLINE=[ON|OFF]); +-- Rebuild all indexes in a table with using parameters +USE [DATABASE_NAME]; +ALTER INDEX ALL ON [SCHEMA.TABLE] +REBUILD WITH (FILLFACTOR=[FILL_FACTOR_VALUE_BETWEEN_0_100], ONLINE=[ON|OFF]); +------------------------------------------------------ +-- Updating database tables without causing blocking +-- You need to take into consideration, possible dirty-read issues when using this approach +UPDATE [TABLE_NAME] WITH (READPAST) +SET … +WHERE … +------------------------------------------------------ +-- 4. Maintenance-Related Tips +------------------------------------------------------ +-- Truncating a data/log file +USE [DBName]; +DBCC SHRINKFILE ([Data_Log_LogicalName],TRUNCATEONLY); +-- Renaming a Windows login +ALTER LOGIN "[Domain or Server Name]\[Windows Username]" +WITH NAME="[New Domain or New Server Name]\[Windows Username]"; +-- Renaming a SQL Server login +ALTER LOGIN "[SQL Server Login Name]" +WITH NAME="[New SQL Server Login Name]"; +-- Creating Logins for orphaned SQL Server users +USE [DBName]; +EXEC sp_change_users_login 'Auto_Fix', '[UserName]', NULL, '[Password]'; +-- Changing the Database Owner in a SQL Server Database (SQL Login) +USE [DBName]; +EXEC sp_changedbowner '[SQL_Login_Name]'; +-- Changing the Database Owner in a SQL Server Database (Windows Login) +USE [DBName]; +EXEC sp_changedbowner '[DomainNameUserName]'