2011-07-03 39 views
6

Trước hết .. xin lỗi vì tiếng Anh xấu của tôi, tôi hy vọng được hiểu.Chuỗi truy vấn trong lệnh SQL C#

Tôi hoạt động với LINQ, SQL là mới đối với tôi.

tôi đang cố gắng để làm điều tiếp theo: i có phương pháp tiếp theo trên 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; 
} 

Tôi có trang ví dụ: items.aspx?nID=144

làm thế nào tôi có thể làm điều đó lệnh SELECT sẽ với chuỗi truy vấn và sẽ lấy giá trị

từ bảng "mục" theo id (nID) hiển thị trên địa chỉ?

Bảng có thiết kế ví dụ: id, title, bla, main.

+0

Tại sao bạn không sử dụng một số ORM? Sau đó bạn có thể sử dụng LINQ. – svick

Trả lời

6

Hãy thử một cái gì đó như thế này:

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

Hãy thử điều này:

Chú ý đến các (Request.QueryString["nID"] ?? "0").ToString() nó thực sự importent, do đó bạn sẽ không có được ngoại lệ khi không có truy vấn.

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; 
    } 
Các vấn đề liên quan