简体   繁体   English

如何使用 Python 将文本文件中的数据插入 SQL 服务器表?

[英]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') cursor.execute("""INSERT INTO employee(empid,name) pyodbc.ProgrammingError: ('SQL 包含 0 个参数标记,但提供了 1 个参数', 'HY000')

Text file data looks like文本文件数据看起来像

empid|Name
1|'Ram'
cursor.execute("""INSERT INTO employee(empid,name)
                  VALUES(?, ?)
                  """, row)

and if this doesn't work, assuming row is an array, try this:如果这不起作用,假设 row 是一个数组,试试这个:

cursor.execute("""INSERT INTO employee(empid,name)
                  VALUES(?, ?)
                  """, row[0], row[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 CSV 和文本文件中的 python 插入 SQL 服务器表 - insert into SQL Server table using python from CSV and Text file 从文本分隔符插入数据 | 文件到 python 脚本中的 SQL 服务器表 - Insert data from text delimiter | file into SQL Server table in python script 如何使用 Python 将 SQL 数据插入数据库? - How do you insert SQL data into a database using Python? 如何使用 Python 以最佳方式将用户的数据插入到文件中? - How do you insert data from the user into the file with the most optimal using Python? 如何将数据从SQL表转换为Excel文件? - How do you turn data from SQL table into an Excel File? 如何从文本文件中获取数据,然后在 Python 文件中使用提取的数据? - How do you grab data from a text file, then use the extracted data in the Python file? 使用文本文件中的 python 插入 mysql 表 - insert into mysql table using python from text file 使用 Python 创建表并插入到 SQL 服务器 - Create table and Insert to SQL Server using Python 如何使用 python 从一行中剪切文本并将 append 剪切到文本文件中的另一行? - How do you cut text from a line and append it to another line in text file using python? 使用 pymssql 将数据插入 SQL Server 表 - Insert Data to SQL Server Table using pymssql
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM