I am currently writing a program that will take data from an excel spreadsheet and insert it into a sql server table that I have created within the program.
I have previously assigned the datetime column to be a nvarchar(250) for the purpose of getting the overall programme to work, however when I go to change it to datetime, the data is inputted into the wrong columns? The rest of the code worked with the nvarchar datatype aswell.
import pyodbc
connection_string = r'connection_string'
data = 'file_path'
conn = pyodbc.connect(connection_string)
cur = conn.cursor()
createtable = """
create table table1(
ID Int NULL,
Date datetime(250) NULL,
City nvarchar(250) NULL,
Country nvarchar(250) NULL,
Image nvarchar(250) NULL,
Length nvarchar(250) NULL,
Date_Of_capture nvarchar(250) NULL,
Comments nvarchar(1000) NULL
)"""
truncatetable = """truncate table table1"""
with open(data) as file:
file.readline()
lines = file.readlines()
if cur.tables(table="table1").fetchone():
cur.execute(truncatetable)
for line in lines:
cols = line.split(',')
cols = line.replace("'", "")
sql = "INSERT INTO table1 VALUES({}, '{}', '{}', '{}', '{}', '{}','{}','{}')".format(cols[0], cols[1],cols[2], cols[3], cols[4], cols[5], cols[6], cols[7])
cur.execute(sql)
else:
cur.execute(createtable)
for line in lines:
cols = line.split(',')
sql = "INSERT INTO table1 VALUES({}, '{}', '{}', '{}', '{}', '{}','{}','{}')".format(cols[0], cols[1],cols[2], cols[3], cols[4], cols[5], cols[6], cols[7])
cur.execute(sql)
conn.commit()
conn.close()
I would expect the date column to show as a datetime data type whilst being contained within one column however it changes the tables so that all the columns are incorrect and each digit of the date is within a different column?
Any help is greatly appreciated. Thank you.