I have a csv file with several records that I am trying to import into a SQL table via a Python script. My csv file (now reduced to) just one row of 1s. Here is what I am trying to do (after successfully connecting to the database etc etc…):
JavaScript
x
9
1
def add_records():
2
with open('C:/testing/myCSV.csv') as csvFile:
3
4
for row in csvFile:
5
cursor.execute(
6
"INSERT INTO MY_Table (thing1, thing2, thing3, thing4, thing5)"
7
"VALUES (?)", row
8
)
9
No matter how I format the data in the csv (right now it’s all 1s) I get the error:
There are more columns in the INSERT statement than values specified in the VALUES clause
Advertisement
Answer
You need to specify a value (or ?
placeholder) in the values
clause for each column you’re inserting:
JavaScript
1
5
1
cursor.execute(
2
"INSERT INTO MY_Table (thing1, thing2, thing3, thing4, thing5)"
3
"VALUES (?, ?, ?, ?, ?)", row
4
)
5
EDIT:
row
is just a simple line read from a CSV file. You should probably use a csv reader to break it up to its individual components:
JavaScript
1
8
1
with open('C:/testing/myCSV.csv') as csvFile:
2
csvReader = csv.reader(csvFile)
3
for row in csvReader:
4
cursor.execute(
5
"INSERT INTO MY_Table (thing1, thing2, thing3, thing4, thing5)"
6
"VALUES (?, ?, ?, ?, ?)", row
7
)
8