构造函数连接数据库: public SqlHelper() { string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString; conns = new SqlConnection(conn); } 打开数据库连接: private SqlConnection Getconn() { if (conns.State == ConnectionState.Closed) { conns.Open(); } return conns; }
执行带参数的增删改: public int ExecuteNonQuery(string cmdText, SqlParameter[] paras, CommandType ct) { int res; using (cmd = new SqlCommand(cmdText, Getconn())) { cmd.CommandType = ct; cmd.Parameters.AddRange(paras); res = cmd.ExecuteNonQuery(); } return res; } 执行带参数的查询: public DataTable Execuquery(string cmdText, SqlParameter[] paras, CommandType ct) { DataTable dt = new DataTable(); using (cmd = new SqlCommand(cmdText, Getconn())) { cmd.CommandType = ct; cmd.Parameters.AddRange(paras); sdr = cmd.ExecuteReader(); dt.Load(sdr); sdr.Close(); return dt; } }