0

我有这个更新方法,请问我的sql语句是否正确?因为我尝试更新 ID 号并将其更改为数据库中现有的 ID 号,所以它无论如何都会更新,甚至不会尝试错误捕获它。

我现在的代码是:

    public void Update()
    {
        sc.Open();

        try
        {
            using (cmd = new SqlCommand(@"UPDATE TableVotersInfo SET Education=@ed, idnum=@idnum, FirstName=@firstname, MiddleName=@middlename, LastName=@lastname, SchoolYear=@schoolyear, ControlNum=@controlnum WHERE id=@id
                                    SELECT @ed, @idnum, @firstname, @middlename, @lastname, @schoolyear, @controlnum
                                    WHERE @id NOT IN (SELECT idNum FROM TableVotersInfo);", sc))
            {
                cmd.Parameters.AddWithValue("@id", _id);
                cmd.Parameters.AddWithValue("@ed", _ed);
                cmd.Parameters.AddWithValue("@idnum", _idnum);
                cmd.Parameters.AddWithValue("@firstname", _firstname);
                cmd.Parameters.AddWithValue("@middlename", _middlename);
                cmd.Parameters.AddWithValue("@lastname", _lastname);
                cmd.Parameters.AddWithValue("@schoolyear", _schoolyear);
                cmd.Parameters.AddWithValue("@controlnum", _controlnum);

                SqlDataReader reader = cmd.ExecuteReader();
                if(reader.Read())
                {
                    MessageBox.Show("ID number already exist!");
                    FAddVoters._cleardata = "0";
                    FAddVoters._checkID = checkID;
                }
                else
                {
                    MessageBox.Show("Data Successfully Updated!");
                    FAddVoters._cleardata = cleardata;
                    FAddVoters._checkID = "0";
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sc.Close();
        }
    }

你能告诉我我在哪里做错了吗?

(编辑)

首要的关键
(来源:akamaihd.net

4

1 回答 1

1

UPDATE命令不会为您返回任何记录,ReadExecuteReader用于SELECT命令。您可以正常更新ExecuteNonQuery并使用try-catch以了解是否有问题:

public void Update()
{
    sc.Open();
    try {
        using (cmd = new SqlCommand(@"UPDATE TableVotersInfo SET Education=@ed, idnum=@idnum, FirstName=@firstname, MiddleName=@middlename, LastName=@lastname, SchoolYear=@schoolyear, ControlNum=@controlnum WHERE id=@id
                                SELECT @ed, @idnum, @firstname, @middlename, @lastname, @schoolyear, @controlnum
                                WHERE @id NOT IN (SELECT idNum FROM TableVotersInfo);", sc))
        {
            cmd.Parameters.AddWithValue("@id", _id);
            cmd.Parameters.AddWithValue("@ed", _ed);
            cmd.Parameters.AddWithValue("@idnum", _idnum);
            cmd.Parameters.AddWithValue("@firstname", _firstname);
            cmd.Parameters.AddWithValue("@middlename", _middlename);
            cmd.Parameters.AddWithValue("@lastname", _lastname);
            cmd.Parameters.AddWithValue("@schoolyear", _schoolyear);
            cmd.Parameters.AddWithValue("@controlnum", _controlnum);

            cmd.ExecuteNonQuery();// <-- this is what you want
            MessageBox.Show("Data Successfully Updated!");
            FAddVoters._cleardata = cleardata;
            FAddVoters._checkID = "0";
        }
    } catch (SqlException ex) {
        if(ex.Number == 2627)//duplicated primary key 
        {
           MessageBox.Show("ID number already exist!");
           FAddVoters._cleardata = "0";
           FAddVoters._checkID = checkID;
        } else {
           MessageBox.Show("There was some error while attempting to update!\nTry again later.");
        }
    }
    finally {
        sc.Close();
    }
}

更新

如果您不能将idnum主键设为主键(由于某些设计原因),您必须执行一些查询来检查是否存在,如下所示:

public bool ExistsKey(string keyField, string table, string value, SqlConnection con){      
  try {
   if(con.State != ConnectionState.Open) con.Open();
   using(SqlCommand com = new SqlCommand(
                string.Format("IF EXISTS(SELECT * FROM {0} WHERE {1}='{2}') SELECT 1 ELSE SELECT 0", 
                             table, keyField, value), con)){
     var result = com.ExecuteScalar();
     return result != null && (int)result == 1;
   }
  } catch {
    return false;
  }
  finally {
    con.Close();
  }      
}
//Then use that method in your code like this:

if(ExistsKey("idnum", "TableVotersInfo", _idnum.ToString(), sc)){
  MessageBox.Show("ID number already exist!");
  FAddVoters._cleardata = "0";
  FAddVoters._checkID = checkID;
} else {
  //perform your update here ...
}
于 2013-10-30T20:41:19.033 回答