Skip to content

Commit ccd9161

Browse files
Add files via upload
1 parent c0dd3d9 commit ccd9161

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed

SQL Code Block Prepend Tool.py

+120
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
"""
2+
SQL File Importer for SQL Server and PostgreSQL
3+
4+
Description:
5+
This Python script facilitates the automated import of SQL files into either SQL Server or PostgreSQL databases.
6+
It is designed to traverse specified directories, identify all SQL files, and insert their contents into a designated database table.
7+
The script supports dynamic database connection configurations for both SQL Server and PostgreSQL, allowing users to specify
8+
the target database system at runtime. Additionally, it intelligently handles file encodings to ensure compatibility with various
9+
file origins.
10+
11+
Usage:
12+
- Set the 'database_system' variable to either 'sql_server' or 'postgres' based on the target database system.
13+
- Configure connection parameters for both SQL Server and PostgreSQL in the 'sql_server_config' and 'postgres_config' dictionaries, respectively.
14+
- Specify the target directory in the 'directory' variable. The script will process all .sql files within this directory and its subdirectories.
15+
- Execute the script. It will establish a connection to the specified database, and for each .sql file found, it will insert its contents into the database.
16+
- Ensure the target database has a table named 'FileTextImport' with an appropriate schema to store file names, line numbers, text content, and file directories.
17+
18+
Features:
19+
- Dynamic database system selection allows for flexible deployment across different database environments.
20+
- Comprehensive file encoding support ensures the script can handle .sql files from various sources without data corruption.
21+
- Automatic traversal of specified directories and subdirectories for thorough file processing.
22+
- Detailed error logging provides insights into any issues encountered during file processing.
23+
- Ensures data integrity by committing transactions upon successful insertion of file contents into the database.
24+
25+
Note:
26+
Before running the script, ensure that the 'FileTextImport' table exists in your target database with columns for file name, line number, text content, and file directory. Additionally, adjust the connection parameters in the configuration dictionaries to match your database server settings.
27+
28+
29+
--SQl Server
30+
DROP TABLE IF EXISTS FileTextImport;
31+
GO
32+
33+
CREATE TABLE FileTextImport (
34+
ID INTEGER IDENTITY(1,1) PRIMARY KEY,
35+
InsetDate DATETIME DEFAULT GETDATE() NULL,
36+
FileName NVARCHAR(255) NULL,
37+
LineNumber INTEGER NULL,
38+
myText NVARCHAR(MAX) NULL,
39+
FileDirectory NVARCHAR(MAX) NULL
40+
);
41+
42+
--Postgres
43+
DROP TABLE IF EXISTS public."FileTextImport";
44+
45+
CREATE TABLE public.filetextimport (
46+
ID SERIAL PRIMARY KEY,
47+
InsertDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
48+
FileName VARCHAR(255),
49+
LineNumber INTEGER,
50+
myText TEXT,
51+
FileDirectory TEXT
52+
);
53+
54+
"""
55+
56+
57+
import os
58+
import pyodbc
59+
import psycopg2
60+
61+
# Define target database system
62+
# Options: 'sql_server' or 'postgres'
63+
database_system = 'postgres' # Change this to 'postgres' / 'sql_server' as needed
64+
65+
# SQL Server connection parameters
66+
sql_server_config = {
67+
'server': 'DESKTOP-D324ETP\\SQLEXPRESS01',
68+
'database': 'mytest',
69+
'trusted_connection': 'yes'
70+
}
71+
72+
# PostgreSQL connection parameters
73+
postgres_config = {
74+
'database': 'test_db',
75+
'user': 'postgres',
76+
'password': 'Letmein01!',
77+
'host': 'localhost'
78+
}
79+
80+
# Directory to search for .sql files
81+
directory = r'C:\tmp\\'
82+
83+
def import_sql_files(directory, database_system):
84+
if database_system == 'sql_server':
85+
cnxn_string = f"DRIVER={{SQL Server}};SERVER={sql_server_config['server']};DATABASE={sql_server_config['database']};Trusted_Connection={sql_server_config['trusted_connection']};"
86+
cnxn = pyodbc.connect(cnxn_string)
87+
elif database_system == 'postgres':
88+
cnxn_string = f"dbname={postgres_config['database']} user={postgres_config['user']} password={postgres_config['password']} host={postgres_config['host']}"
89+
cnxn = psycopg2.connect(cnxn_string)
90+
else:
91+
raise ValueError("Unsupported database system specified.")
92+
93+
cursor = cnxn.cursor()
94+
95+
# Walk through the directory
96+
for root, dirs, files in os.walk(directory):
97+
for file in files:
98+
if file.endswith(".sql"):
99+
file_path = os.path.join(root, file)
100+
file_directory = os.path.dirname(file_path) # Get the directory of the file
101+
try:
102+
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
103+
line_number = 1 # Initialize line number
104+
for line in f:
105+
if database_system == 'sql_server':
106+
insert_stmt = "INSERT INTO FileTextImport (FileName, LineNumber, myText, FileDirectory) VALUES (?, ?, ?, ?)"
107+
elif database_system == 'postgres':
108+
insert_stmt = "INSERT INTO FileTextImport (FileName, LineNumber, myText, FileDirectory) VALUES (%s, %s, %s, %s)"
109+
# Execute insert statement
110+
cursor.execute(insert_stmt, (file, line_number, line, file_directory))
111+
line_number += 1
112+
except Exception as e:
113+
print(f"Error reading {file_path}: {e}")
114+
# Commit transactions and close connection
115+
cnxn.commit()
116+
cursor.close()
117+
cnxn.close()
118+
119+
import_sql_files(directory, database_system)
120+
print('Task Completed')

0 commit comments

Comments
 (0)