43 lines
1.1 KiB
Python
43 lines
1.1 KiB
Python
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()
|