The reason I ask, is that origionally all references and examples pointed towards Method 2.
But Method 1 seems to do so much more in so much less code. Surely its
- neater,
- Better
- Easier to read / follow
- and has features like converting DBNulls to null. Rather than having to do it myself.
- Handles opening and closing of the connection/ data readers.
I cant think of any reasons for method 2 over using method 1.
(Method 2 could probably have a using clause, but due to so much code, it was put in a seperate function to be called from else wher, and hence closing it closed the datareader making data inacccessable.)
Anyway, I am seriously thinking about going back and changing over my entire webservice to use method 1 as it seems so much better and maintainable. Can anyone suggest otherwise?
Method 1:
using (var db = Database.OpenConnectionString(Library.Properties.Settings.Default.dbConnString, "System.Data.SqlClient"))
{
Int32 AccNo = db.QuerySingle("SELECT AccNo FROM Tasks WHERE TaskID = " + TaskID);
}
Method 2:
sqlComm = new SqlCommand();
sqlCon = new SqlConnection();
sqlComm.Connection = sqlCon;
sqlCon.ConnectionString = global::Library.Properties.Settings.Default.dbConnString;
sqlComm.CommandText = "SELECT AccNo FROM Tasks WHERE TaskID = " + TaskID;
sqlCon.Open();
SqlDataReader data = sqlComm.ExecuteReader();
while (data.Read())
{
Int32 AccNo = (Int32)data["AccNo"];
}
sqlCon.Close();
sqlComm.Dispose();
if (data != null)
data.Close();
ExecuteScalarmethod, to get just a single value.