DataTableが必要な場合は、次のメソッドが短く、複雑さが軽減されます。
public DataTable GetDataForSql(string sql, string connectionString)
{
using(SqlConnection connection = new SqlConnection(connectionString))
{
using(SqlCommand command = new SqlCommand())
{
command.CommandType = CommandType.Text;
command.Connection = connection;
command.CommandText = sql;
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
DataTable data = new DataTable();
data.Load(reader);
return data;
}
}
}
}
利用方法:
try{
DataTable results = GetDataForSql("SELECT * FROM Table;", ApplicationSettings["ConnectionString"]);
}
catch(Exception e)
{
//Logging
//Alert to user that command failed.
}
ここでDataAdapterを使用する必要は実際にはありません。実際には、必要なものではありません。Update、Delete、またはInsertコマンドが使用されている場合、なぜ例外などをキャッチするのが面倒なのですか?それはあなたがやりたいことにぴったりではありません。
SelectCommandプロパティは特別なことは何もしないことに注意することが重要です-SelectCommandが実行されても、渡されたコマンドはすべて実行されます-結果セットが返されることを期待し、結果が返されない場合は、空のデータセット。
これは、(とにかくこれを行う必要があります)ユーザーがクエリできるようにするテーブルにSELECT権限のみを明示的に付与する必要があることを意味します。
編集
他の質問に答えるために、SqlDataReaderはReadOnly
、読み取り専用のファイアホーススタイルのカーソルを介して機能するためです。これが効果的に意味することは次のとおりです。
while(reader.Read()) //Reads a row at a time moving forward through the resultset (`cursor`)
{
//Allowed
string name = reader.GetString(reader.GetOrdinal("name"));
//Not Allowed - the read only bit means you can't update the results as you move through them
reader.GetString(reader.GetOrdina("name")) = name;
}
レコードを移動するときにレコードを更新できないため、読み取り専用です。ただし、結果セットを取得するために実行するSQLがデータを更新できない理由はありません。