使用WriteToServer方法插入数据datetime列会给出异常

时间:2015-07-13 15:04:56

标签: c# sql-server datetime sqlbulkcopy

我正在尝试将use DBI; use strict; use warnings; my $dbh = DBI->connect( "DBI:mysql:DBNAME;host=localhost", 'root', 'password'); my $sth = $dbh->prepare("select distinct(department) from amc_info"); $sth->execute(); while (my $depart= $sth->fetchrow_array()) { my $sth1 = $dbh->prepare("select * into outfile '$depart\.txt' fields terminated by ',' lines terminated by '\n' from amc_info where department='$depart'"); $sth1->execute(); $sth1->finish(); } $sth->finish(); 插入到数据类型为datetime的列中。该值是使用DateTime分配的,因此我知道代码中的类型不正确。

我得到的例外是:

DateTime.Now

这就是我指定数据表列的方式:

The given value of type String from the data source cannot be converted
to type datetime of the specified target column.

以下是我设置数据的方式:

DataTable HODetails = new DataTable();
HODetails.Columns.Add("MasterID", typeof(long));
HODetails.Columns.Add("ItemID", typeof(int));
HODetails.Columns.Add("SubCategoryID", typeof(int));
HODetails.Columns.Add("BatchNo", typeof(string));
HODetails.Columns.Add("ExpiryDate", typeof(DateTime));

那么为什么HODetails.Rows[HODetails.Rows.Count - 1]["ItemID"] = Convert.ToInt32(lblItemId.Text); HODetails.Rows[HODetails.Rows.Count - 1]["MasterID"] =HOReceipt_ID; HODetails.Rows[HODetails.Rows.Count - 1]["SubCategoryID"] = SubCatID; HODetails.Rows[HODetails.Rows.Count - 1]["BatchNo"] = Convert.ToString(txtBatchNo.Text == "" ? "" : txtBatchNo.Text); HODetails.Rows[HODetails.Rows.Count - 1]["ExpiryDate"] = DateTime.Now; 认为“数据源中String类型的值无法转换为datetime类型”?

1 个答案:

答案 0 :(得分:0)

我的问题解决了 我改变了我的writeToServer方法

                if (DtWithTableName.Rows.Count > 0)
                {
                using (SqlBulkCopy s = new SqlBulkCopy(strConnection))
                {

                try
                {
                    s.DestinationTableName = "HOMaterialReceiptDetails";
                    s.ColumnMappings.Add("MasterID", "MasterID");
                    s.ColumnMappings.Add("ItemID", "ItemID");
                    s.ColumnMappings.Add("SubCategoryID", "SubCategoryID");
                    s.ColumnMappings.Add("ExpiryDate", "ExpiryDate");
                    s.ColumnMappings.Add("BrandName", "BrandName");
                    s.ColumnMappings.Add("Qty", "Qty");
                    s.ColumnMappings.Add("FreeQty", "FreeQty");
                    s.ColumnMappings.Add("ReturnQty", "ReturnQty");
                    s.ColumnMappings.Add("ReplacementQty", "ReplacementQty");
                    s.WriteToServer(DtWithTableName);
                }
                catch (Exception)
                {

                    IsInserted = false;
                }

            }
        }