如何在读取CSV记录时将空字符串转换为null? [英] How to convert empty string to null while reading CSV records?

查看:102
本文介绍了如何在读取CSV记录时将空字符串转换为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取CSV文件并根据CSV文件的标题动态创建数据库表.

但是在读取csv数据并将其转储到相关表时遇到了问题.当我有一个具有十进制数据类型的列并且CSV字段包含空白,因此将其视为字符串并且低于错误时,就会出现问题.

错误:

无法将参数值从字符串转换为十进制.

我正在使用

当sqlbulk复制试图将这些数据转储到SQL Server数据库表中时,会出现问题.

解决方案

我认为您可能需要进行列映射.如果您使用的是SqlBulkCopy,则可以使用本文中介绍的一些内容:

在使用SqlBulkCopy将数据表转换为SQL表

I am reading CSV files and dynamically creating database tables based on headers of CSV files.

But getting problem while reading csv data and dumping in to relevant tables. The problem comes when I have a column with decimal datatype and CSV fields contains blank so it is treated as string and getting below error.

Error :

Failed to convert parameter value from a String to a Decimal.

I am using CSV Helper and through class map, maybe I can achieve this but I am dynamically creating structure based on CSV files so I can't define any fixed class.

Here is 1 answer I found which might be helpful in case of class map: Using CsvHelper can I translate white space to a nullable?

Sample Record :

Problem occurs when sqlbulk copy tries to dump those data in SQL Server database table.

解决方案

I think that you might need to do column mapping. If you are using SqlBulkCopy you can use some of what is described on this post:

Mapping columns in a DataTable to a SQL table with SqlBulkCopy

这篇关于如何在读取CSV记录时将空字符串转换为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆