2017-05-08 13 views
2

你可以幫助我嗎? 我真的不知道該怎麼做。試圖比較一個給定的ID與存儲在數據庫

我想要做的是,當我給它一個ID,比較它與存儲在數據庫中的另一個ID。

public Rubro GetRubroById(int GivenId) 
{ 

    Rubro rubro = new Rubro(); 
    SqlCommand command = new SqlCommand 

    ("SELECT * FROM Rubro WHERE GivenId = Id", con); 
    try 
    { 
     con.Open(); 
     SqlDataReader reader = command.ExecuteReader(); 
     while (reader.Read()) 
     { 
      rubro.Id = reader.GetInt32(0); 
      rubro.Name = reader.GetString(1); 
     } 
     con.Close(); 
    } 
    catch (SqlException ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 

    return rubro; 
} 
+2

你沒有添加你的'SqlParameter' – Jonesopolis

回答

1

的問題是,在您通過SQL GivenId變量有GetRubroById方法GivenId變量沒有關係。儘管它們有共同的名稱,但它們存在於系統的不同部分。

您需要的值傳遞給使用參數的語句:

SqlCommand command = new SqlCommand("SELECT * FROM Rubro WHERE @GivenId = Id", con); 
command.Parameters.Add("@GivenId", SqlDbType.Int); 
command.Parameters["@GivenId"].Value = GivenId; // rename to givenId 

你應該遵守.NET命名約定重命名GivenIdgivenId

+1

這實際上有效!非常感謝! –

1

您必須將值傳遞給SQL查詢參數:

using(var command = new SqlCommand("SELECT * FROM Rubro WHERE Id = @GivenId", con)) 
{ 
    try 
    { 
     command.Parameters.Add("@GivenId", SqlDbType.Int).Value = GivenId; 
     con.Open(); 
     using(var reader = command.ExecuteReader()) 
     while (reader.Read()) 
     { 
      rubro.Id = reader.GetInt32(0); 
      rubro.Name = reader.GetString(1); 
     } 
     con.Close(); 
    } 
    catch (SqlException ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
} 
相關問題