////// 获取连接字符串 /// private static readonly string constr = ConfigurationManager.ConnectionStrings["dbUser"].ConnectionString; ////// 返回受影响行数(非查询语句) /// /// SQL语句 /// 参数化查询 ///public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(constr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteNonQuery(); } } } /// /// 返回查询结果集中的第一行第一列 /// /// SQL语句 /// 参数化查询 ///public static object ExecuteScalar(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(constr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteScalar(); } } } /// /// 返回查询结果有多条数据,数据放在数据库中 /// /// SQL语句 /// 参数化查询 ///public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection()) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteReader(); } } } /// /// 返回查询结果有多条数据,数据放在本地缓存中 /// /// SQL语句 /// 参数化查询 ///public static DataTable ExecuteDataSet(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(constr)) { conn.Open() using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); DataSet dataset = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dataset); return dataset.Tables[0]; } } } /// /// 将数据库中的Null转化为null /// /// ///public static object OutputNull(object value) { if (value == DBNull.Value) return null; else return value; } /// /// 将输入数据的null转化为数据库中Null /// /// ///public static object InputNull(object value) { if (value == null) return DBNull.Value; else return value; } }