分类: C#/.net
2013-02-22 17:59:21
以下抽象出了ADO.NET中 最常用的几个方法。还在继续优化和扩展中
public class DBHelper { static readonly String conSql = ConfigurationManager.ConnectionStrings["sql"].ToString(); public static SqlDataReader ExecuteReader(String sql, CommandType type, params SqlParameter[] pars) { SqlConnection con = new SqlConnection(conSql); return Common(con, type, sql, pars).ExecuteReader(CommandBehavior.CloseConnection); } public static bool ExecuteNonQuery(String sql, CommandType type, params SqlParameter[] pars) { using (SqlConnection con = new SqlConnection(conSql)) { return Common(con, type, sql, pars).ExecuteNonQuery() > 0; } } public static Object ExecuteScalar(String sql, CommandType type, params SqlParameter[] pars) { using (SqlConnection con = new SqlConnection(conSql)) { return Common(con, type, sql, pars).ExecuteScalar(); } } public static SqlDataAdapter ExcuteDataSet(String sql, CommandType type, params SqlParameter[] pars) { SqlDataAdapter da = null; SqlConnection con = new SqlConnection(conSql); da = new SqlDataAdapter(Common(con, type, sql, pars)); return da; } private static SqlCommand Common(SqlConnection con, CommandType type, String sql, params SqlParameter[] pars) { SqlCommand cmd = new SqlCommand(sql, con); foreach (SqlParameter item in pars) { if (item != null) { cmd.Parameters.Add(item); } } cmd.CommandText = sql; cmd.CommandType = type; cmd.Connection.Open(); return cmd; } }