如果你只是想要一個數據表,然後下面的方法很短,降低了複雜性:
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 - 這是不是真的爲了你想要的。如果使用更新,刪除或插入命令,爲什麼還要去捕捉異常等等?它不適合你想要做的事情。
這是重要到注的SelectCommand屬性沒有做什麼特別的東西 - 在執行SelectCommand中時,它仍然會運行任何命令傳遞給它 - 它只是expects一個結果被返回,如果沒有結果返回,那麼它返回一個空的數據集。
這意味着(你應該這樣做),你應該顯式授予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不能更新數據。
duplicate - http://stackoverflow.com/questions/4900630/dataadapter-fill-command-prohibit-write-operation – Tobsey
另一種選擇可能是使用DataTable.Load方法帶一個SqlDataReader,所以你沒有除了DataTable.Load(command.ExecuteReader())以外的任何其他操作。 – dash
另外請注意,你不應該僅僅依靠這一點 - 確保你恰當地允許表的SELECT權限('GRANT SELECT ON [Table] TO [User]')。有人可能按照SELECT * FROM User; DROP TABLE User;的語句輸入內容:這在技術上是一個返回結果集的sql語句:SelectCommand屬性就是將抽象數據加載到適配器中 - 它不會做任何事情來防止錯誤的sql被運行。 – dash