我习惯于使用SqlHelper
该类,因此想修改现有代码以使用它。
现有代码
public string GetData()
{
string message = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "usp_getdata";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = reader[0].ToString();
}
}
}
return message;
}
我能做的最多就是这个。我怎样才能使这更好。基本思路是尽量减少代码行数,利用SqlHelper,也用dataset代替datareader。
public string GetData()
{
string message = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlConnection connection = new SqlConnection(conStr);
SqlCommand cmd = (SqlCommand)SqlHelper.CreateCommand(connection, "usp_getdata");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Notification = null;
SqlDependency dependency = new SqlDependency(cmd);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
message = ds.Tables[0].Rows[0]["Message"].ToString();
return message;
}