【问题标题】:Error while trying to insert Python dataframe into SQL table尝试将 Python 数据帧插入 SQL 表时出错
【发布时间】:2022-02-22 07:17:43
【问题描述】:

我正在尝试将 .csv 文件的内容插入 SQL Server 数据库。我可以在我的 csv 文件中插入没有 nulls 的列。很少有列很少blanks,因此我无法将这些特定列与其他列一起插入。我已经创建了一个这样的表;

CREATE TABLE [main].[table1](
    [Record_ID] [int] IDENTITY(1,1) NOT NULL,
    [account_id] [nvarchar](max) NULL,
    [business_name] [nvarchar] (max) NULL,
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

如上所述,account_idbusiness_name 列中的空白很少。我可以毫无错误地插入其他列。当我尝试插入这两列时,会出现这样的错误,

ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 4 (""): The supplied value is not a valid instance of data type float. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision. (8023) (SQLExecDirectW)')

不知道为什么每次我尝试插入 csv 文件内容时都会得到这个。我已经在我的insert 命令中处理了这个问题,null 将被允许。

插入命令:

cursor.execute("INSERT INTO main.table1(account_id,business_name) values(?,?)", row.account_id, row.business_name)

谁能告诉我如何解决这个问题?

任何帮助将不胜感激。

【问题讨论】:

  • account_id [nvarchar](max) 真的吗?这对我来说很有趣。同样,[business_name] [nvarchar] (max)
  • 除此之外... SQL Server 2008 不再受 Microsoft 支持,并且已经有几年不支持了。您应该将数据库迁移到受支持的较新版本的 SQL Server。
  • Edit您的问题包含更多信息。根据错误消息中的ProgrammingError,您似乎正在尝试从 Python 脚本插入数据,那么当错误被抛出时该代码试图做什么?
  • 提供的值不是浮点数据类型的有效实例问题是:为什么你的脚本认为目标表中的数据类型是浮点数(当有您发布的表格中没有浮动)
  • ......有人几乎总是和你有同样的错误。 stackoverflow.com/questions/66068980/… 基本上你需要用 something 替换空白或空值,否则它认为它是一个浮点数

标签: sql-server sql-server-2008 sql-insert create-table


【解决方案1】:

我只是简单地包含了将 NaN 替换为 0 的函数,它现在在我创建要加载的数据框后立即使用以下代码行成功加载所有行 (df)

df = df.fillna(value=0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    相关资源
    最近更新 更多