【问题标题】:How do you insert data from text file into SQL Server table using Python?如何使用 Python 将文本文件中的数据插入 SQL Server 表?
【发布时间】:2020-12-01 05:50:43
【问题描述】:
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")

我收到以下错误

cursor.execute("""INSERT INTO employee(empid,name) pyodbc.ProgrammingError: ('SQL 包含 0 个参数标记,但 1 参数已提供', 'HY000')

文本文件数据的样子

empid|Name
1|'Ram'

【问题讨论】:

    标签: python python-3.x pysqlite


    【解决方案1】:
    cursor.execute("""INSERT INTO employee(empid,name)
                      VALUES(?, ?)
                      """, row)
    

    如果这不起作用,假设 row 是一个数组,试试这个:

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

    【讨论】:

    • IndexError: list index out of range 这是我遇到的错误
    • 那么行的结构是什么?像它是一个数组,如果是,数组的长度是否对所有行都是固定的?
    • 行由分隔符分隔 |
    • 你能举个例子吗?行的值
    • 添加有问题请查看
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    相关资源
    最近更新 更多