1 public class SqlHelper
2 {
3 public static string SqlConnectionStr = ConfigurationManager.ConnectionStrings[
"SqlCon"].ConnectionString;
4
5 public static DataTable Query(
string sql)
6 {
7 using (SqlConnection con =
new SqlConnection(SqlConnectionStr))
8 {
9 using (SqlDataAdapter da =
new SqlDataAdapter(sql, con))
10 {
11 DataTable dt =
new DataTable();
12 try
13 {
14 con.Open();
15 da.Fill(dt);
16 return dt;
17 }
18 catch (Exception ex)
19 {
20 throw ex;
21 }
22 finally
23 {
24 if (con.State ==
ConnectionState.Open)
25 con.Close();
26 }
27 }
28 }
29 }
30
31 public static void Excute(
string sql)
32 {
33 using (SqlConnection con =
new SqlConnection(SqlConnectionStr))
34 {
35 using (SqlCommand cmd =
new SqlCommand(sql, con))
36 {
37 try
38 {
39 con.Open();
40 cmd.ExecuteNonQuery();
41 }
42 catch (Exception ex)
43 {
44 throw ex;
45 }
46 finally
47 {
48 if (con.State ==
ConnectionState.Open)
49 con.Close();
50 }
51 }
52 }
53 }
54
55 public static void Excute(
string sql, CommandType cmdType, SqlParameter[] spArr)
56 {
57 using (SqlConnection con =
new SqlConnection(SqlConnectionStr))
58 {
59 using (SqlCommand cmd =
new SqlCommand(sql, con))
60 {
61 foreach (SqlParameter sp
in spArr)
62 {
63 cmd.Parameters.Add(sp);
64 }
65 try
66 {
67 cmd.CommandType =
cmdType;
68 con.Open();
69 cmd.ExecuteNonQuery();
70 }
71 catch (Exception ex)
72 {
73 throw ex;
74 }
75 finally
76 {
77 if (con.State ==
ConnectionState.Open)
78 con.Close();
79 }
80 }
81 }
82 }
83 }
转载于:https://www.cnblogs.com/zhaotianff/p/5681732.html