public class SqlHelper { public static string connstr= ConfigurationManager.ConnectionStrings["Connstr"].ConnectionString; /// <summary> /// 執行增刪改 /// ...
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; } }View Code
這是簡單的sqlHelper,保存一下。