简体   繁体   English

数据源中String类型的给定值无法转换为指定目标列的float类型

[英]The given value of type String from the data source cannot be converted to type float of the specified target column

I was wondering if someone could help. 我想知道是否有人可以提供帮助。 I am attempting to read a CSV file in C# and import it's data into a table i have created in SQL 2008. 我试图在C#中读取CSV文件并将其数据导入我在SQL 2008中创建的表中。

For some reason i keep getting the following error: 由于某种原因,我不断收到以下错误:

"The given value of type String from the data source cannot be converted to type float of the specified target column." “数据源中String类型的给定值无法转换为指定目标列的float类型。”

Complete Stack Trace: 完整堆栈跟踪:

System.Data.SqlClient.SqlBulkCopy.ConvertValue(Object value, _SqlMetaData metadata, Boolean isNull, Boolean& isSqlType, Boolean& coercedToDataFeed)
System.Data.SqlClient.SqlBulkCopy.ReadWriteColumnValueAsync(Int32 col)
System.Data.SqlClient.SqlBulkCopy.CopyColumnsAsync(Int32 col, TaskCompletionSource`1 source)
System.Data.SqlClient.SqlBulkCopy.CopyRowsAsync(Int32 rowsSoFar, Int32 totalRows, CancellationToken cts, TaskCompletionSource`1 source)
System.Data.SqlClient.SqlBulkCopy.CopyBatchesAsyncContinued(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
System.Data.SqlClient.SqlBulkCopy.CopyBatchesAsync(BulkCopySimpleResultSet internalResults, String updateBulkCommandText, CancellationToken cts, TaskCompletionSource`1 source)
System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalRestContinuedAsync(BulkCopySimpleResultSet internalResults, CancellationToken cts, TaskCompletionSource`1 source)
System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalRestAsync(CancellationToken cts, TaskCompletionSource`1 source)
System.Data.SqlClient.SqlBulkCopy.WriteToServerInternalAsync(CancellationToken ctoken)
System.Data.SqlClient.SqlBulkCopy.WriteRowSourceToServerAsync(Int32 columnCount, CancellationToken ctoken)
System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table, DataRowState rowState)
System.Data.SqlClient.SqlBulkCopy.WriteToServer(DataTable table)
RMBEventReportingSystemPOC.Admin.ProcessFile(String strFilename) in \Admin.aspx.cs:line 159

Please find below the code i am using. 请在下面找到我正在使用的代码。 Please let me know where i have gone wrong : 请让我知道我哪里出错了:

StatusLabel.Text = "File Process status: File process started!";
try
{

    //var fileName = string.Format(strFilename, Directory.GetCurrentDirectory());

    SqlConnection con = new SqlConnection(@"**ConnectionString**");

    string filepath = Server.MapPath("~/uploads/") + strFilename;
    StreamReader sr = new StreamReader(filepath);
    string line = sr.ReadLine();
    string[] value = line.Split(';');
    DataTable dt = new DataTable();
    DataRow row;
    foreach (string dc in value)
    {
        if (dc == "Month" || dc == "Year" || dc == "Reply")
            dt.Columns.Add(new DataColumn(dc, typeof(int)));
        else if (dc == "CostPerHead" || dc == "TotalCost")
            dt.Columns.Add(new DataColumn(dc, typeof(float)));
        else
            dt.Columns.Add(new DataColumn(dc));
    }

    while (!sr.EndOfStream)
    {
        value = sr.ReadLine().Split(';');
        if (value.Length == dt.Columns.Count)
        {
            row = dt.NewRow();


            //fix up default values                        
            value[1] = value[1] == "" ? "0" : value[1].ToString().Trim();
            value[2] = value[2] == "" ? "0" : value[2].ToString().Trim();
            value[3] = value[3] == "" ? "0.00" : string.Format("{0:0.00}",value[3].ToString());
            value[4] = value[4] == "" ? "0.00" : string.Format("{0:0.00}",value[4].ToString());
            value[7] = value[7] == "" ? "0" : value[7].ToString().Trim();

            row.ItemArray = value;

            dt.Rows.Add(row);
        }
    }

    ////fix up default values

    for (int i = 0; i < dt.Rows.Count; i++)
    {

        dt.Rows[i][1] = int.Parse(dt.Rows[i][1].ToString().Trim());
        dt.Rows[i][2] = int.Parse(dt.Rows[i][2].ToString().Trim());
        dt.Rows[i][3] = Math.Round(float.Parse(dt.Rows[i][3].ToString() + ".00"), 2);
        dt.Rows[i][4] = Math.Round(float.Parse(dt.Rows[i][4].ToString() + ".00"), 2);

        dt.Rows[i][7] = dt.Rows[i][7].ToString() == "" ? 0 : int.Parse(dt.Rows[i]["Reply"].ToString().Trim());
    }

    SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
    bc.DestinationTableName = "Guestlist";
    bc.BatchSize = dt.Rows.Count;
    // add column mappings if necessary               
    con.Open();
    bc.WriteToServer(dt);
    bc.Close();
    con.Close();


    StatusLabel.Text = "File Process status: File process completed! " + dt.Rows.Count.ToString() + " records imported.";
    StatusLabel.CssClass = "success";
}
catch (Exception exx)
{

    StatusLabel.Text = "File Process status: File process failed!: " + exx.Message;
    StatusLabel.CssClass = "error";
}

any pointers would be greatly appreciated. 任何指针将不胜感激。

SqlBulkCopy.WriteToServer(DataTable) fails with confusing messages if the column order of the DataTable differs from the column order of the table definition in your database (when this causes a type or length incompatibility). 如果DataTable的列顺序与数据库中表定义的列顺序不同(当这会导致类型或长度不兼容时),则SqlBulkCopy.WriteToServer(DataTable)因混淆消息而失败。 Apparently the WriteToServer method does not map column names. 显然, WriteToServer方法不映射列名。

One or more of your columns are defined as float type in the database. 您的一个或多个列在数据库中定义为float类型。

However, in the CSV file the column value is a string or contains a value that cannot be converted to a float type. 但是,在CSV文件中,列值是字符串或包含无法转换为浮点类型的值。

The columns you are converting at 您要转换的列

dt.Rows[i][3] = Math.Round(float.Parse(dt.Rows[i][3].ToString() + ".00"), 2);
dt.Rows[i][4] = Math.Round(float.Parse(dt.Rows[i][4].ToString() + ".00"), 2);

may contain a floating point number already. 可能已包含浮点数。 By appending ".00" you are now making it invalid and hence the conversion fails. 通过附加“.00”,您现在使其无效,因此转换失败。

Depending on the data, either remove the conversion or make conditional use of it. 根据数据,删除转换或有条件地使用它。

You should use an object array, instead of a string array for the variable called value. 对于名为value的变量,您应该使用对象数组而不是字符串数组。

Then call Convert.ToFloat() method on any data you assign to it which is meant to end up in a float column in the database. 然后对分配给它的任何数据调用Convert.ToFloat()方法,这意味着最终在数据库的float列中。

When you set the object array to the row.ItemArray, the fields which are float in the database will be floats in your array too, and you should be able to submit to the database ok. 当您将对象数组设置为row.ItemArray时,数据库中浮动的字段也将浮动在您的数组中,您应该能够提交到数据库ok。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 来自数据源的 String 类型的给定值无法转换为指定目标列的 nvarchar 类型 - The given value of type String from the data source cannot be converted to type nvarchar of the specified target column 来自数据源的String类型的给定值不能转换为指定目标列的varbinary类型 - The given value of type String from the data source cannot be converted to type varbinary of the specified target column 数据源中String类型的给定值无法转换为指定目标列的int类型 - The given value of type String from the data source cannot be converted to type int of the specified target column SqlBulkCopy - 来自数据源的 String 类型的给定值无法转换为指定目标列的货币类型 - SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column 来自数据源的 String 类型的给定值无法转换为指定目标列的 int 类型。 - The given value of type String from the data source cannot be converted to type int of the specified target column.' SQlBulkCopy 无法将数据源中 DateTime 类型的给定值转换为指定目标列的 int 类型 - SQlBulkCopy The given value of type DateTime from the data source cannot be converted to type int of the specified target column SqlBulkCopy引发异常:无法将数据源中String类型的给定值转换为指定目标列的bigint类型 - SqlBulkCopy throws exception: The given value of type String from the data source cannot be converted to type bigint of the specified target column SQL批量复制“使用ASP.NET无法将数据源中String类型的给定值转换为指定目标列的类型日期时间” - SQL Bulk Copy “The given value of type String from the data source cannot be converted to type datetime of the specified target column” using ASP.NET 在LINQ dat source / gridview中使用文本框值作为参数:“String”类型的值无法转换为“Double”类型 - Using textbox value as parameter in LINQ dat source/gridview : A value of type 'String' cannot be converted to type 'Double' “T”类型的值无法转换为 - Value of type 'T' cannot be converted to
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM