我正在尝试使用 SqlBulkCopy() 将 DataTable 保存到 SQL Server,但出现异常

发布于 2025-01-12 04:35:31 字数 1382 浏览 1 评论 0原文

下面是我将 DataTable 保存到 SQL Server 的代码:

SqlBulkCopy bcp = new SqlBulkCopy(con);
bcp.DestinationTableName = "Hawalas";

ListtoDataTableConverter converter = new ListtoDataTableConverter();

DataTable dt = converter.ToDataTable(hawalastoInsert);

// SqlConnection con = new SqlConnection(@"Server=SALEHI\SQLEXPRESS;Database=Exchange; Integrated Security=True;");

try
{
    bcp.WriteToServer(dt);
    MessageBox.Show("Saved successfully");
}
catch(Exception ex)
{
    MessageBox.Show("Err"+ ex.ToString());
}

DataTable 包含其值为日期和时间的字段;在执行时,我分配了日期和时间值,如下所示:

string str = "01/01/0001 00:00:00";

DateTime datetime1 = DateTime.ParseExact(str, "dd/MM/yyyy HH:mm:ss", null);
var uk = datetime1.ToString(new CultureInfo("en-GB"));
string t = uk.ToString().Replace('/', '-');
                
hawala.FlagDateTime = DateTime.Parse(t); 
                

注意:hawala 是一个类,我们创建该类的对象,并将它们保存在列表中,最后使用

ListtoDataTableConverter converter = new ListtoDataTableConverter(); 
DataTable dt = converter.ToDataTable(listTobeConverted);

我们将列表更改为 DataTable

这是错误:

error

这是保存到 SQL Server 之前我的 DataTable DateTime 值:

DataTableValues

Here is my code to save the DataTable to SQL Server:

SqlBulkCopy bcp = new SqlBulkCopy(con);
bcp.DestinationTableName = "Hawalas";

ListtoDataTableConverter converter = new ListtoDataTableConverter();

DataTable dt = converter.ToDataTable(hawalastoInsert);

// SqlConnection con = new SqlConnection(@"Server=SALEHI\SQLEXPRESS;Database=Exchange; Integrated Security=True;");

try
{
    bcp.WriteToServer(dt);
    MessageBox.Show("Saved successfully");
}
catch(Exception ex)
{
    MessageBox.Show("Err"+ ex.ToString());
}

The DataTable contains fields which their values are date and time; while executing I assigned the date and time value as shown here:

string str = "01/01/0001 00:00:00";

DateTime datetime1 = DateTime.ParseExact(str, "dd/MM/yyyy HH:mm:ss", null);
var uk = datetime1.ToString(new CultureInfo("en-GB"));
string t = uk.ToString().Replace('/', '-');
                
hawala.FlagDateTime = DateTime.Parse(t); 
                

Note: hawala is a class which we create object of that and we keep them in a List finally using

ListtoDataTableConverter converter = new ListtoDataTableConverter(); 
DataTable dt = converter.ToDataTable(listTobeConverted);

We change the list to DataTable

Here is the error:

error

Here are my DataTable DateTime values before saving to SQL Server:

DataTableValues

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文