我在Jupyter Notebook中有一个代码,该代码应将数据上传到SQL Server并进行转换。
不寻常的是,当我在单独的单元格中运行此代码时,它可以正常工作,但是当我将其包含在一个单元格(或本例中的2个)中时,最后一条语句(带有“ update”)将不会执行。在这种情况下,query_update
是唯一未处理的语句。知道为什么吗?
# cell 1
import pyodbc
import pandas as pd
import subprocess
connection = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=server;"
"Database=db;"
"Trusted_Connection=yes;", autocommit=True)
cursor = connection.cursor()
# cell 2
query_preload = '''
truncate table _Distr_for_clients;
ALTER TABLE _Distr_for_clients DROP COLUMN [Период];
ALTER TABLE _Distr_for_clients DROP COLUMN [Дистрибьютор];
ALTER TABLE _Distr_for_clients DROP COLUMN [Medicine_Key];
'''
cursor.execute(query_preload)
print('truncated')
subprocess.Popen(r'bcp [BI_analysis]..[_distr_for_clients] in "T:\work\_DDS\data_original\distr\2019-10 Протек\distr for clients.txt" -SRU-BISVR-01 -T -c -CRAW -t\t -F2')
print('data loaded from txt')
query_transform = '''
ALTER TABLE _Distr_for_clients ADD [Период] Date;
ALTER TABLE _Distr_for_clients ADD [Дистрибьютор] VARCHAR(10);
ALTER TABLE _Distr_for_clients ADD [Medicine_Key] VARCHAR(15);
'''
cursor.execute(query_transform)
print('added columns')
date = "'2019.10.01'"
query_update = '''
update _Distr_for_clients set [Период] = CONVERT(date,{});
update _Distr_for_clients set [Дистрибьютор] = 'distr';
update _Distr_for_clients SET _Distr_for_clients.[Medicine_Key] = _Dim_Distributor_Med_Name_Med_Key.[Medicine_Key] from _Dim_Distributor_Med_Name_Med_Key WHERE _Distr_for_clients.[NM_MED] = _Dim_Distributor_Med_Name_Med_Key.[Medicine_Name];
'''.format(date)
cursor.execute(query_update)
print('updated added columns')