代码之家  ›  专栏  ›  技术社区  ›  Sartorialist

ASP。net MVC:输入字符串格式不正确

  •  1
  • Sartorialist  · 技术社区  · 8 年前

    我正在尝试写入数据库,但收到“输入字符串格式不正确”错误。我假设是最后两列上的数据类型,但我不确定如何更改。在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();
                        }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   CodingYoshi    8 年前

    错误 输入字符串的格式不正确 很可能是由于列中的某个值无法转换为 int . 如果SQL中的数据类型为 money 那么您应该尝试转换为 decimal 而不是 内景 . 每行尝试以下操作:

    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 Tales example of paratmetrized query .