2009-03-31 20 views
3

これは私が知っている非常に簡単になるだろう。私は実際の標準とasp.netでSQLを使用する非常に多くの異なる方法を見てきました。私が知りたいのは、asp.netのSQLデータベースからきれいに選択し、複数のレコードを取得する方法です。たとえば、すべてのユーザーIDを選択します。Asp.Netで選択してください

String sql = 
    "SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'"; 

string strCon = System.Web 
         .Configuration 
         .WebConfigurationManager 
         .ConnectionStrings["SocialSiteConnectionString"] 
         .ConnectionString; 

SqlConnection conn = new SqlConnection(strCon); 
SqlCommand comm = new SqlCommand(sql, conn); 
conn.Open(); 

/* 
This is where I need to know how to retrieve the information from the 
above command(comm). I am looking for something similiar to php's 
mysql_result. I want to access the records kind of like an array or some 
other form of retrieving all the data. 
Also when the new SqlCommand is called...does that actual run the 
SELECT STATEMENT or is there another step. 
*/ 

conn.Close(); 
+0

SqlCommandが注射を妨げるために+1します。 – jww

答えて

6

私はと思いますこれはあなたが探しているものです。

String sql = "SELECT [UserId] FROM [UserProfiles] WHERE NOT [UserId] = 'CurrentUserId'"; 

string strCon = System.Web 
         .Configuration 
         .WebConfigurationManager 
         .ConnectionStrings["SocialSiteConnectionString"].ConnectionString; 

SqlConnection conn = new SqlConnection(strCon); 
SqlCommand comm = new SqlCommand(sql, conn); 
conn.Open(); 
SqlDataReader nwReader = comm.ExecuteReader(); 
while (nwReader.Read()) 
{ 
    int UserID = (int)nwReader["UserID"]; 
    // Do something with UserID here... 
} 
nwReader.Close(); 
conn.Close(); 

しかし、全体的なアプローチでは多くの調整を使用できます。まず、ConnectionStringへのアクセスを単純化することから始めてください。たとえば、あなたがGlobal.asax.csファイルに次を追加することができます。

using System; 
    using System.Configuration; 

    public partial class Global : HttpApplication 
    { 
     public static string ConnectionString; 

     void Application_Start(object sender, EventArgs e) 
     { 
      ConnectionString = ConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString; 
     } 
     ... 
    } 

を今、あなたのコード全体、ちょうど使用してアクセス:いっそ

SqlConnection conn = new SqlConnection(Global.ConnectionString); 

、クラスを作成するもので「配管」は隠されています。私のコードで同じクエリを実行するには、私はちょうど入力したい:

 using (BSDIQuery qry = new BSDIQuery()) 
     { 
      SqlDataReader nwReader = qry.Command("SELECT...").ReturnReader(); 
      // If I needed to add a parameter I'd add it above as well: .ParamVal("CurrentUser") 
      while (nwReader.Read()) 
      { 
       int UserID = (int)nwReader["UserID"]; 
       // Do something with UserID here... 
      } 
      nwReader.Close(); 
     } 

これは DALを使用して一例に過ぎません。ただし、接続文字列やコマンドや接続オブジェクトが作成または管理されておらず、「BSDIQuery」(これに加えて多くのことが表示されています)に注意してください。最も頻繁に行う作業によって、あなたのアプローチは異なります。

+0

それは素晴らしい仕事、それはまさに私が探していたものです! – user84786

+0

信頼性の面ではかなり悪いです。例外が発生しても、例外が発生した場合、例外が発生します。 –

+0

Joel - 入力した追加コードを参照してください。私はあなたに同意しますが、 "基本的な"質問に答えるためには、より深い問題を提起する前に答えてみたいです。 –

1

SqlCommandを作成しても、それはまったく実行されません。

ExecuteReaderまたはそれに類するものを呼び出すと、コマンドが実行されます。

すべての結果をメモリに取り込む場合は、DataSet/DataTableを探してください。彼らのためのチュートリアルhere - またはネット上に他の多くがあり、まともなADO.NETの本でもそれらをカバーします。

を入力しない場合は、をすべて一度にメモリにフェッチしたい場合は、ExecuteReaderメソッドを使用します。これはデータベースカーソルのようなSqlDataReaderを返します。一度に行を読み込み、それぞれの列を尋ねて、毎回次の行に移動するにはReadを呼び出します。

+0

結果をメモリにフェッチしたくないのですが、ExecuteReaderを呼び出すとどのように結果にアクセスできますか? – user84786

3

時間のほとんどは、私はこの(私も接続プーリングのアプローチを使用していますことに注意してください)を使用します。

public DataTable ExecuteQueryTable(string query) 
    { 
     return ExecuteQueryTable(query, null); 
    } 

    public DataTable ExecuteQueryTable(string query, Dictionary<string, object> parameters) 
    { 
     using (SqlConnection conn = new SqlConnection(this.connectionString)) 
     { 
      conn.Open(); 

      using (SqlCommand cmd = conn.CreateCommand()) 
      { 
       cmd.CommandText = query; 

       if (parameters != null) 
       { 
        foreach (string parameter in parameters.Keys) 
        { 
         cmd.Parameters.AddWithValue(parameter, parameters[parameter]); 
        } 
       } 

       DataTable tbl = new DataTable(); 
       using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
       { 
        da.Fill(tbl); 
       } 

       return tbl; 
      } 
     } 
    } 
+0

これはうれしいです...しかし、私はそれがIEnumerable を辞書ではなく受け入れるのを見たいと思います。深いネスティングを避けるためにあなたのusingステートメントを積み重ねることができます。あなたのパラメータのタイプを推測して、あなたは.FillよりもむしろDataTable.Loadを使うことができます。 –

+0

私はそれが私には良い気分になるからです。 StyleCopをすべて実行しているので、私が使っているような使い方をする理由があります。そして、私はIEnumerable に同意します。 –

2

をここでは、既存のコードの適応です:

String sql = "SELECT [UserId] FROM [UserProfiles] WHERE [UserId] != @CurrentUserId"; 

string strCon = System.Web 
         .Configuration 
         .WebConfigurationManager 
         .ConnectionStrings["SocialSiteConnectionString"].ConnectionString; 

DataTable result = new DataTable(); 
using (var conn = new SqlConnection(strCon)) 
using (var cmd = new SqlCommand(sql, conn)) 
{ 
    cmd.Parameters.Add("@CurrentUserID", SqlDbType.Int).Value = CurrentUserID; 
    conn.Open(); 

    result.Load(cmd.ExecuteReader()); 
} 
0

PHPには、.NETで

while ($row = mysql_fetch_array ($result)) 
{ 
    //this assumes you're doing something with foo in loop 
    $foo = $row["userid"]; 

    //using $foo somehow 
} 

、のような何かをしたいのに対し、あなたは別の何かをします。私がPHPのバックグラウンドに由来していると信じて、PHPから.NETへの移行は容易ではありません。奇妙に見えることがたくさんあります。しかし、しばらくすると、それは意味をなさない!ちょうどそれを突き出す。私は個人的にはそれがより好きです。

//assuming you have a DataSet called myDataSet 
for (int i = 0; i < myDataSet.Tables[0].Rows.Count; i++) 
{ 
    //likewise assuming here you're doing something with foo in loop 
    string foo = myDataSet.Tables[0].Rows[i]["userid"].ToString(); 

    //similarly do something with foo in loop 
} 

これは、PHPスニペットと同じことを行います。これは、あなたが言うようにデータセットを持っていると仮定すると、これを行うことができます。

+0

どちらも悪いです。同じ変数を何度も何度も設定しますか?ループ内で他の作業をするためにそれを使用する場合は、コードスニペットにコメントを追加して、それをより明確にします。 –

+0

良いキャッチ。 )私はあなたがループ内のそれらの変数で何かをやっていると仮定していました。 – Anjisan