sql update命令不更新数据库

时间:2015-01-21 13:41:26

标签: c# sql

我有这个按钮,根据程序中给出的ID更新空表格单元格。

代码没有错误,但不会更新表...

cmd4.Parameters.AddWithValue("@id",ActiveAthNum);

我尝试将它保留为String并将其转换为int(表格单元格为ID和点数)

AfRows返回0 ...但查询本身在SQL中运行完美... ActiveAthNum和PointsGiven变量具有它们应该具有的值。

代码:

private void btnSavePoints_Click(object sender, EventArgs e)
{
    con = new SqlConnection(CONNSTRING);
    cmd4 = new SqlCommand("UPDATE SadaTestTable SET Points = @pts WHERE id = @id");
    cmd4.Parameters.AddWithValue("@id", ActiveAthNum);
    PointsGiven = Convert.ToInt32(tbPointsGiven.Text);
    cmd4.Parameters.AddWithValue("@pts", PointsGiven);
    cmd4.Connection = con;
    int AfRows;
    con.Open();
    AfRows = cmd4.ExecuteNonQuery();
}

4 个答案:

答案 0 :(得分:0)

问题可能在于ID参数的类型。尝试指定正确的DbType:

cmd4.Parameters.Add("id", SqlDbType.Char); //set proper type as in table
cmd4.Parameters["id"].Value = "";

答案 1 :(得分:0)

你真的应该把那个数据库调用放到Try ... Catch ... Finally block。

您的数据库的默认语言是什么?很久以前,当DB语言设置为US-EN而不是“数据库默认值”时,我看到了这种类型的错误(没有更新但没有错误)。

数据库会抛出有关正在更改的默认语言的“错误”,但它不会在我的ASP代码中触发错误。关于错误代码的东西没有注册为错误 - 我必须为该特定错误号编码才能绕过它。我只看过两次,但是在两家不同的公司......

答案 2 :(得分:0)

cmd4.Parameters.AddWithValue("@id", SqlDbType.Int).Value = ActiveAthNum;

答案 3 :(得分:0)

问题是因为您没有指定数据类型

private void btnSavePoints_Click(object sender, EventArgs e)
{
    con = new SqlConnection(CONNSTRING);
    cmd4 = new SqlCommand("UPDATE SadaTestTable SET Points = @pts WHERE id = @id",con);
    cmd4.Parameters.AddWithValue("@id", Datatype.Char);//if the datatype in the database is char but if the data type in the database is int then is datatype.int
    PointsGiven = Convert.ToInt32(tbPointsGiven.Text);
    cmd4.Parameters.AddWithValue("@pts", PointsGiven);
     try
   {
         con.open();//here open my connection 
         cmd4.connection = con;  
        Afrows = cmd4.ExecutenonQuery();//Execute my query
   }
  catch
   {
      throw;//possible exceptions in the system
   }
  finally
   {
       con.Close();//closing connections
   }


}