自己写的SqlHelper类
今天老师复习了ADO ,因为代码的重复使用问题,所以老师就让我们写了sqlhelper类 这是我写的sqlhelper
public class SqlHelper
{
string constr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
public int ExecuteNonQuery( string commandtext,params SqlParameter[] prms) {
using (SqlConnection conn = new SqlConnection(constr)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand(commandtext,conn)){
if (prms != null) {
cmd.Parameters.AddRange(prms);
}
int r = cmd.ExecuteNonQuery();
return r;
}
}
}
public object ExecuteScalar(string commandtext,params SqlParameter[] prms)
{
using (SqlConnection conn = new SqlConnection(constr)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand(commandtext, conn)) {
if (prms != null) {
cmd.Parameters.AddRange(prms);
}
object obj = cmd.ExecuteScalar();
return obj;
}
}
}
public SqlDataReader ExecuteReader(string commandtext, params SqlParameter[] prms) {
SqlConnection conn = new SqlConnection(constr); //此处不能使用using如果使用的话 内边就调用不到连接对象了
conn.Open();
using (SqlCommand cmd = new SqlCommand(commandtext, conn)) {
if (prms != null) {
cmd.Parameters.AddRange(prms);
}
SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); //当你关闭reader的时候 SqlConnection也就关闭了
return reader;
}
}
public DataTable datatable(string commandtext) {
SqlDataAdapter adapter = new SqlDataAdapter(commandtext, constr);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
}