简体   繁体   中英

insert into SQL Server table using python from CSV and Text file

I am trying to insert data from a CSV file and also from a textfile into SQL SERVER SSMS version 18.7. Below is my code.

import pyodbc
import csv
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=????;'
                      'Database=???;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()

with open('C:/python/names.txt', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        cursor.execute("""INSERT INTO TESTPYTHON (id,name) VALUES(%s,%s)""", row)

conn.commit()
cursor.close()
print ("Done")

When I run the query I get the following error.

 cursor.execute("""INSERT INTO TESTPYTHON (id,name) VALUES(%s,%s)""", row)
pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')

Process finished with exit code 1

Can someone help we with this also how should I separate the values if I am using text files?

Maybe try using the unload operator, like cursor.execute("""INSERT INTO TESTPYTHON (id,name) VALUES(%s,%s)""", *row)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM