1 public static class SqlHelper 2 { 3 public static readonly string connstr = 4 ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; 5 6 public static SqlConnection OpenConnection() 7 { 8 SqlConnection conn = new SqlConnection(connstr); 9 conn.Open();10 return conn;11 }12 13 public static int ExecuteNonQuery(string cmdText,14 params SqlParameter[] parameters)15 {16 using (SqlConnection conn = new SqlConnection(connstr))17 {18 conn.Open();19 return ExecuteNonQuery(conn, cmdText, parameters);20 }21 }22 23 public static object ExecuteScalar(string cmdText,24 params SqlParameter[] parameters)25 {26 using (SqlConnection conn = new SqlConnection(connstr))27 {28 conn.Open();29 return ExecuteScalar(conn, cmdText, parameters);30 }31 }32 33 public static DataTable ExecuteDataTable(string cmdText,34 params SqlParameter[] parameters)35 {36 using (SqlConnection conn = new SqlConnection(connstr))37 {38 conn.Open();39 return ExecuteDataTable(conn, cmdText, parameters);40 }41 }42 43 public static int ExecuteNonQuery(SqlConnection conn,string cmdText,44 params SqlParameter[] parameters)45 {46 using (SqlCommand cmd = conn.CreateCommand())47 {48 cmd.CommandText = cmdText;49 cmd.Parameters.AddRange(parameters);50 return cmd.ExecuteNonQuery();51 }52 }53 54 public static object ExecuteScalar(SqlConnection conn, string cmdText,55 params SqlParameter[] parameters)56 {57 using (SqlCommand cmd = conn.CreateCommand())58 {59 cmd.CommandText = cmdText;60 cmd.Parameters.AddRange(parameters);61 return cmd.ExecuteScalar();62 }63 }64 65 public static DataTable ExecuteDataTable(SqlConnection conn, string cmdText,66 params SqlParameter[] parameters)67 {68 using (SqlCommand cmd = conn.CreateCommand())69 {70 cmd.CommandText = cmdText;71 cmd.Parameters.AddRange(parameters);72 using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))73 {74 DataTable dt = new DataTable();75 adapter.Fill(dt);76 return dt;77 }78 }79 }80 81 public static object ToDBValue(this object value)82 {83 return value == null ? DBNull.Value : value;84 }85 86 public static object FromDBValue(this object dbValue)87 {88 return dbValue == DBNull.Value ? null : dbValue;89 }90 }