执行标量:从数据库方法获取单个值以从数据库中检索单个值(例如,聚合值)。
cmd1.Connection = GetConnection();
cmd1.CommandText = "SELECT treatment FROM appointment WHERE patientid = " + text;
if(cmd.ExecuteScalar()==null)
{
var treatment = cmd.ExecuteScalar();
}
其他方式:ExecuteReader()
try
{
cmd1.CommandText ="SELECT treatment FROM appointment WHERE patientid=@patientID";
cmd1.Parameters.AddWithValue("@patientID", this.DropDownList1.SelectedValue);
conn.Open();
SqlDataReader dr = cmd1.ExecuteReader();
while (dr.Read())
{
int PatientID = int.Parse(dr["treatment"]);
}
reader.Close();
((IDisposable)reader).Dispose();//always good idea to do proper cleanup
}
catch (Exception exc)
{
Response.Write(exc.ToString());
}