我习惯使用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,并使用数据集代替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;
}