Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you insert data from text file into SQL Server table using Python?

import pyodbc
import csv
conn = pyodbc.connect('Driver=ODBC Driver 17 for SQL Server;'
                      'Server=SIS10647\MSSQLSERVER14;'
                      'Database=LeelaVenkatesh;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()

cursor.execute('''

               CREATE TABLE employee
               (
               empid int,
               Name nvarchar(50)
               )

               ''')

with open('C:\PYTHON\Textfiles/1.txt') as f:
    reader = csv.reader(f)
    for row in reader:
        cursor.execute("""INSERT INTO employee(empid,name)
                          VALUES(%s, %s)
                       """, row)
conn.commit()
cursor.close()
print("Done")

I am getting the following error

cursor.execute("""INSERT INTO employee(empid,name) pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')

Text file data looks like

empid|Name
1|'Ram'
like image 361
Chanukya Avatar asked Dec 28 '25 19:12

Chanukya


1 Answers

cursor.execute("""INSERT INTO employee(empid,name)
                  VALUES(?, ?)
                  """, row)

and if this doesn't work, assuming row is an array, try this:

cursor.execute("""INSERT INTO employee(empid,name)
                  VALUES(?, ?)
                  """, row[0], row[1])
like image 112
illusion Avatar answered Dec 30 '25 16:12

illusion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!