Chanukya
Chanukya

Reputation: 5893

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'

Upvotes: 3

Views: 1923

Answers (2)

asarak
asarak

Reputation: 1

empid|Name
1|'Ram'
try this
empid,Name
1,Ram
with 
cursor.execute("""INSERT INTO employee(empid,name)
                  VALUES(?, ?)
                  """, row[0], row[1])

Upvotes: 0

illusion
illusion

Reputation: 1301

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])

Upvotes: 1

Related Questions