Список SQL пуст для чтения второго файла с использованием python - PullRequest
0 голосов
/ 27 марта 2020

Я использую следующий python код для следующего:

  1. Чтение нескольких файлов, расположенных в папке.
  2. Чтение каждого оператора, разделенного ';'.
  3. Выполнение каждого оператора по одному.
import os
import pyodbc as po

filepath = r'C:\Users\<username>\Documents\Shell_Scripts\SQL\Test'

conn = po.connect('DRIVER={SQL Server};SERVER=<server_name>;DATABASE=<db>;UID=<usrnm>;PWD=<pswd>')

for script in os.listdir(filepath):
    print('File path : ')
    with open(filepath+'\\'+script,'r') as insert:
        print(insert)
        sqlFile = insert.read()
        print('\nFile content :\n',sqlFile)
        SQL = sqlFile.split(';')
        SQL = [x for x in SQL if '\n' in SQL]
        print('\nSQL statements converted to list :',SQL)
        for statement in SQL:
            statement.strip('\n')
            print('\nStatement in execution : ',statement)
            with conn.cursor() as cur:
                cur.execute(statement)
                if 'Select' in statement:
                    print('Table output \n',cur.fetchall())
                elif 'Insert' in statement:
                    print('{0} row(s) inserted.\n'.format(cur.rowcount))
                elif 'Update' in statement:
                    print('{0} row(s) updated. \n'.format(cur.rowcount))
                elif 'Delete' in statement:
                    print('{0} row(s) deleted. \n'.format(cur.rowcount))
                elif 'Create' in statement:
                    print('Table created.')
                elif 'Alter' in statement:
                    print('Alteration Done')
                else: 
                    print("Statement dont have any DDL/DML commands")
                conn.commit()
        SQL = []
        sqlFile = []
    print('\nFile executed : ',script)

conn.close()

Но получение пустого списка SQL для 2-го файла.

Вывод:

File path :
<_io.TextIOWrapper name='C:\\Users\\<user>\\Documents\\Shell_Scripts\\SQL\\Test\\Test_SQL_file.sql' mode='r' encoding='cp1252'>

File content :
 /*****Creating a new table test and adding values to it***********/
Drop table if exists test;
Create table test (id int, name nvarchar(15));
Insert into test values (32,'Prakash');

Insert into test values (23,'Adam');

Select *
from test;


SQL statements converted to list : ['/*****Creating a new table test and adding values to it***********/\nDrop table if exists test', '\nCreate table test (id int, name nvarchar(15))', "\nInsert into test values (32,'Prakash')", "\n\nInsert into test values (23,'Adam')", '\n\nSelect * \nfrom test', '\n']

Statement in execution :  /*****Creating a new table test and adding values to it***********/
Drop table if exists test
Statement dont have any DDL/DML commands

Statement in execution :
Create table test (id int, name nvarchar(15))
Table created.

Statement in execution :
Insert into test values (32,'Prakash')
1 row(s) inserted.


Statement in execution :

Insert into test values (23,'Adam')
1 row(s) inserted.


Statement in execution :

Select *
from test
Table output
 [(32, 'Prakash'), (23, 'Adam')]

Statement in execution :

Statement dont have any DDL/DML commands

File executed :  Test_SQL_file.sql
File path :
<_io.TextIOWrapper name='C:\\Users\\<user>\\Documents\\Shell_Scripts\\SQL\\Test\\Test_SQL_file1.sql' mode='r' encoding='cp1252'>

File content :

ALTER Table test
ADD DOB date;

Update test
set DOB = '1920-03-13'
where name ='Prakash';

Update test
set DOB = '1925-05-20'
where name ='Adam';

Select *
from test
where name = 'Prakash';

Select *
From Test;

SQL statements converted to list : []

File executed :  Test_SQL_file1.sql

Как видите, список SQL пуст при загрузке второго файла.

Сейчас. sql Файлы, которые я читаю, выглядят следующим образом:

Первый файл: Test_SQL_file. sql

/*****Creating a new table test and adding values to it***********/
Drop table if exists test;
Create table test (id int, name nvarchar(15));
Insert into test values (32,'Prakash');

Insert into test values (23,'Adam');

Select * 
from test;

Второй файл: Test_SQL_file1. sql


ALTER Table test 
ADD DOB date;

Update test 
set DOB = '1920-03-13' 
where name ='Prakash';

Update test 
set DOB = '1925-05-20' 
where name ='Adam';  

Select * 
from test 
where name = 'Prakash';

Select * 
From Test;

Какие ошибки я делаю?

...