【问题标题】:ASP.net MVC: Input String Was Not In Correct FormatASP.net MVC:输入字符串格式不正确
【发布时间】:2018-01-20 23:42:28
【问题描述】:

我正在尝试写入数据库并收到“输入字符串格式不正确”错误。我假设它是最后两列的数据类型,但我不确定如何更改。在 SQL Server 中,它们都是 money 数据类型。代码如下:

string query = null;
                    for (int i = 0; i < result.Tables[0].Rows.Count; i++)
                    {
                        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
                        query = "INSERT INTO Upload(Email, TimeStamp, EmployeeId, Name, Title, Department, Race, Gender, AnnualizedBase, AnnualizedTCC) VALUES ('" 
                            + System.Web.HttpContext.Current.User.Identity.GetUserId() + "', "
                            + " '" + DateTime.Now + "', "
                            + " '" + result.Tables[0].Rows[i][0].ToString() + "', "
                            + " '" + result.Tables[0].Rows[i][1].ToString() + "', "
                            + " '" + result.Tables[0].Rows[i][2].ToString() + "', "
                            + " '" + result.Tables[0].Rows[i][3].ToString() + "', "
                            + " '" + result.Tables[0].Rows[i][4].ToString() + "', "
                            + " '" + result.Tables[0].Rows[i][5].ToString() + "', "
                            + Convert.ToInt32(result.Tables[0].Rows[i][6]) + ", "
                            + Convert.ToInt32(result.Tables[0].Rows[i][7])
                            + ")";
                        con.Open();
                       SqlCommand cmd = new SqlCommand(query, con);
                       cmd.ExecuteNonQuery();
                        con.Close();
                    }

【问题讨论】:

  • 请尽快查看如何编写参数化查询。您将从这些错误、这些乱七八糟的代码和 Sql 注入中解脱出来
  • 感谢 cmets。如果我理解正确,我的插入查询将类似于 INSERT INTO TABLE VALUES (@email, @field2, @field3),每个字段的定义如下: var emailparam = new SqlParameter("Email", SqlDbType.文本); emailparam.Value = System.Web.HttpContext.Current.User.Identity.GetUserId(); -- 对吗?

标签: c# sql-server ado.net


【解决方案1】:

错误输入字符串的格式不正确很可能是由于您的列中的值之一无法转换为int。如果 SQL 中的数据类型是 money,那么您应该尝试转换为 decimal 而不是 int。对每一行试试这个:

decimal num;
if (decimal.TryParse(result.Tables[0].Rows[i][6], out num))
{
    // use num because it is indeed a decimal (money in SQL)
}
else
{
    // What do you want to do? Log it and continue to next row?
}

另请阅读Bobby Talesexample of paratmetrized query

【讨论】:

    猜你喜欢
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多