namespace DAL { class SqlHelper { static string conString = "server=.;database=SQLSchool;uid=sa;pwd=sasa"; /// <summary> /// 执行查询返回结果集 /// </summary> /// <param name="safeSql">存储过程名(SQL语句)</param> /// <param name="ps">SQL参数对象集合</param> /// <returns>table</returns> public static DataTable ExecuteTable(string safeSql, SqlParameter[] ps) { //using 块 using (SqlConnection con = new SqlConnection(conString)) { SqlCommand cmd = new SqlCommand(safeSql, con); //设置命令的类型是:存储过程。如果不设,默认是执行的文本,也就是普通的SQL语句 cmd.CommandType = CommandType.StoredProcedure; //默认是执行普通的SQL文本语句如:select * from student //cmd.CommandType = CommandType.Text; if (ps != null && ps.Length > 0) { //把参数添加到命令对象的集合中 cmd.Parameters.AddRange(ps); } con.Open(); SqlDataReader reader = cmd.ExecuteReader();//查询数据:ExecuteReader DataTable table = new DataTable(); table.Load(reader); reader.Close(); con.Close(); return table; } } public static object ExecuteSingle(string safeSql, SqlParameter[] ps)//单个对象:ExecuteSingle { using (SqlConnection con = new SqlConnection(conString)) { SqlCommand cmd = new SqlCommand(safeSql, con); cmd.CommandType = CommandType.StoredProcedure; if (ps != null && ps.Length > 0) { cmd.Parameters.AddRange(ps); } con.Open(); object result = cmd.ExecuteScalar(); con.Close(); return result; } } public static int ExecuteInsertUpdateDelete(string safeSql, SqlParameter[] ps) { using (SqlConnection con = new SqlConnection(conString)) { SqlCommand cmd = new SqlCommand(safeSql, con); cmd.CommandType = CommandType.StoredProcedure; if (ps != null && ps.Length > 0) { cmd.Parameters.AddRange(ps); } con.Open(); int effectedRows = cmd.ExecuteNonQuery();//增、删、改:ExecuteNonQuery con.Close(); return effectedRows; //返回受影响行数(1为成功,0为失败) } } } }