2011-07-03 12 views
6

Przede wszystkim .. przepraszam za mój zły angielski, mam nadzieję, że zostanie zrozumiany.Łańcuch zapytania w poleceniu SQL C#

Jestem regullar do pracy z LINQ, SQL jest dla mnie nowy.

staram się zrobić następną rzeczą: Mam kolejną metodę na C#:

public string niceMethod() 
{ 
    SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;"); 
    string commandtext = "SELECT bla FROM items WHERE main = 1"; 
    SqlCommand command = new SqlCommand(commandtext, connection); 
    connection.Open(); 
    string tDate = (string)command.ExecuteScalar(); 
    connection.Close(); 
    return tDate; 
} 

mam stronę na przykład: items.aspx?nID=144

jak mogę zrobić, że polecenie SELECT będzie z querystringiem, który przyjmie wartość z tabeli "items" z identyfikatorem id (nID) wyświetlanym na adres?

tabeli mają konstrukcję, na przykład: id, title, bla, main.

+0

Dlaczego nie używasz ORM? Możesz wtedy użyć LINQ. – svick

Odpowiedz

6

spróbować czegoś takiego:

int nID = int.Parse(Request.QueryString["nID"].ToString()); 
niceMethod(nID); 

public string niceMethod(int nID) 
{ 
    using (var conn = new SqlConnection("Data Source=server;Initial Catalog=blah;Integrated Security=False;")) 
    using (var cmd = conn.CreateCommand()) 
    { 
     conn.Open(); 
     cmd.CommandText = @"SELECT bla, id, title FROM items WHERE main = @nID"; 
     cmd.Parameters.AddWithValue("@nID", nID); 
     string tDate = cmd.ExecuteScalar().ToString();    
     return tDate; 
    } 
} 
5

Spróbuj tego:

zwrócić uwagę na (Request.QueryString["nID"] ?? "0").ToString() to naprawdę importent więc przyzwyczajenie się wyjątek, gdy nie ma zapytania.

public string niceMethod() 
    { 
     string tDate = ""; 
     string ID = (Request.QueryString["nID"] ?? "0").ToString(); // Get's the nID query, incase there is no query, returns 0. 
     using (SqlConnection connection = new SqlConnection("Data Source=*******;Integrated Security=False;")) 
     { 
      string commandtext = "SELECT bla FROM items WHERE [email protected]"; //@ID Is a parameter 
      SqlCommand command = new SqlCommand(commandtext, connection); 
      command.Parameters.AddWithValue("@ID", ID); //Adds the ID we got before to the SQL command 
      connection.Open(); 
      tDate = (string)command.ExecuteScalar(); 
     } //Connection will automaticly get Closed becuase of "using"; 
     return tDate; 
    }