2011-07-03 15 views
6

まずは..私の悪い英語のために私を許してください、私は理解されることを望みます。SQLコマンドでのクエリ文字列C#

私はLINQで作業するにはregullarですが、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コマンドは次のようになることをクエリーストリングを使用すると、 "items"テーブルのアドレスに表示されるID(nID)によって値

が使用されますか?

テーブルは、例えばデザインを持っている:あなたは文句を言わないときに例外を取得するので、それは本当ににとって必須だ(Request.QueryString["nID"] ?? "0").ToString()

ご注意:これを試してみてください

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

なぜORMを使用しないのですか?その後、LINQを使用することができます。 – svick

答えて

6

はこのような何かを試してみてくださいクエリはありません。

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

id, title, bla, main.

関連する問題