public class SqlHelper { public static string connstr= ConfigurationManager.ConnectionStrings["Connstr"].ConnectionString; /// <summary> /// 执行增删改 /// </summary> /// <param name="sql"></param> /// <param name="parameters"></param> /// <returns></returns> public static int ExecuteNonQuery(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connstr)) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteNonQuery(); } } } /// <summary> /// 返回之后一行一列的数据 /// </summary> /// <param name="sql"></param> /// <param name="parameters"></param> /// <returns></returns> public static object ExecuteScalar(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connstr)) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); return cmd.ExecuteScalar(); } } } /// <summary> /// 返回查询的表 /// </summary> /// <param name="sql"></param> /// <param name="parameters"></param> /// <returns></returns> public static DataTable ExecuteDataTable(string sql, params SqlParameter[] parameters) { using (SqlConnection conn = new SqlConnection(connstr)) { conn.Open(); using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = sql; cmd.Parameters.AddRange(parameters); SqlDataAdapter ada = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); ada.Fill(ds); return ds.Tables[0]; } } } /// <summary> /// 从数据库查询的数据,如果是DBNull就转换成null /// </summary> /// <param name="value"></param> /// <returns></returns> public static object FromDBNull(object value) { if (value == DBNull.Value) { return null; } else { return value; } } /// <summary> /// 把数据插入数据库中,如果是null就转换成DBNull /// </summary> /// <param name="value"></param> /// <returns></returns> public static object ToDBNull(object value) { if (value == null) { return DBNull.Value; } else { return value; } }
这是简单的sqlHelper,保存一下。