2011-07-03 43 views
6

首先..對不起我的英文不好,我希望能夠理解。在SQL命令c中查詢字符串#

我是regullar與LINQ合作,SQL對我來說是新的。

我想要做的下一件事:我已經在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; 
} 

我有頁面,例如:items.aspx?nID=144

我怎麼能做到這一點的SELECT命令會與查詢字符串,並將採取價值

從「項目」表中的id(nID)顯示在地址?

表有例如設計:id, title, bla, main.

+0

爲什麼不使用一些ORM?你可以使用LINQ。 – svick

回答

6

嘗試是這樣的:

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

試試這個:

,請注意(Request.QueryString["nID"] ?? "0").ToString()它真的importent所以你不會得到例外的時候沒有查詢。

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; 
    }