C# SqlBulkCopy 类型不匹配
我有一个包含 10 列的 DataTable,在其中添加一些行后,我想使用 SqlBulkCopy
将其添加到数据库中。
我的问题是,在数据表中我有字符串,数据库中的一些字段分别是十进制和日期。有没有办法将它们转换为所需的数据类型?
I have a DataTable which has 10 columns, and after I add some rows in it, I want to add it to the database using SqlBulkCopy
.
My problem is that in the DataTable I have strings and some fields in the database are decimal and date respectively. Is there a way to convert them to the desired data types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以编程方式向数据表添加列时,您可以指定类型:-
执行批量复制时将遵循这些类型。
编辑
响应用户评论。
当使用信息填充 DataRow 时,如果源数据与目标字段不匹配,则仅需要显式转换。
如果类型相同,直接赋值即可。
例如
When programmatically adding columns to your DataTable, you can specify type:-
These will be honored when you perform the bulk copy.
EDIT
In response to user comment.
When populating the DataRow with information, an explicit conversion is only required if the source data doesn't match the target field.
If the types are the same, you can just assign it.
e.g.
听起来您可能正在代码中的 DataTable 中创建列(而不是通过 DataAdapter 填充,后者会适当地设置列数据类型)。
如果是这种情况,那么您是否可以不只是创建具有正确数据类型的 DataColumns,而不是所有字符串......然后确保在向其中添加行时,将数据转换为适当的类型?
也就是说,您的 DataTable 具有正确的类型和正确的数据,因此 SqlBulkCopy 可以将其以正确形式的数据发送到数据库中。
Sounds like you may be creating the columns in the DataTable in code (as opposed to Filling via a DataAdapter which would set the column data types appropriately).
If that's the case, then can you not just create the DataColumns with the correct data types to start with, instead of all strings...and then ensure when you add rows to it, you convert the data into the appropriate type?
i.e. get to the point where your DataTable has the correct types and data in correctly, so SqlBulkCopy can then blast it into the DB with data already in the correct form.
遇到了同样的问题,我想从包含字符串的 Excel 文件中复制数据,并且我希望它们以双精度形式存储在数据库中。我已经粘贴了与以下问题相关的代码:-
//从第一张表读取数据
//其中产品(产品温度)是数据库中数据类型为浮点型且 Excel 文件中数据类型为字符串的列。
was having the same problem where in I was suppose to copy data from an excel file which had strings and I wanted them to be stored in the database as double. I have pasted the code related to the question below :-
//Read Data from First Sheet
//where product(product temperature) is the a column whose datatype in the database is float and in the excel file is string.