分享一个简单的简单的SQLHelper类
时间:2021-07-01 10:21:17
帮助过:2人阅读
class SqlHelper
2 {
3 public static readonly string connstr =
4 ConfigurationManager.ConnectionStrings[
"dbConnStr"].ConnectionString;
5
6 public static int ExecuteNonQuery(
string cmdText,
7 params SqlParameter[] parameters)
8 {
9 using (SqlConnection conn =
new SqlConnection(connstr))
10 {
11 conn.Open();
12 using (SqlCommand cmd =
conn.CreateCommand())
13 {
14 cmd.CommandText =
cmdText;
15 cmd.Parameters.AddRange(parameters);
16 return cmd.ExecuteNonQuery();
17 }
18 }
19 }
20
21 public static object ExecuteScalar(
string cmdText,
22 params SqlParameter[] parameters)
23 {
24 using (SqlConnection conn =
new SqlConnection(connstr))
25 {
26 conn.Open();
27 using (SqlCommand cmd =
conn.CreateCommand())
28 {
29 cmd.CommandText =
cmdText;
30 cmd.Parameters.AddRange(parameters);
31 return cmd.ExecuteScalar();
32 }
33 }
34 }
35
36 public static DataTable ExecuteDataTable(
string cmdText,
37 params SqlParameter[] parameters)
38 {
39 using (SqlConnection conn =
new SqlConnection(connstr))
40 {
41 conn.Open();
42 using (SqlCommand cmd =
conn.CreateCommand())
43 {
44 cmd.CommandText =
cmdText;
45 cmd.Parameters.AddRange(parameters);
46 using (SqlDataAdapter adapter =
new SqlDataAdapter(cmd))
47 {
48 DataTable dt =
new DataTable();
49 adapter.Fill(dt);
50 return dt;
51 }
52 }
53 }
54 }
55
56 public static SqlDataReader ExecuteDataReader(
string cmdText,
57 params SqlParameter[] parameters)
58 {
59 SqlConnection conn =
new SqlConnection(connstr);
60 conn.Open();
61 using (SqlCommand cmd =
conn.CreateCommand())
62 {
63 cmd.CommandText =
cmdText;
64 cmd.Parameters.AddRange(parameters);
65 return cmd.ExecuteReader(CommandBehavior.CloseConnection);
66 }
67 }
68
69 public static int ExecuteStoredProcedure(
string procName,
70 params SqlParameter[] parameters)
71 {
72 SqlConnection conn =
new SqlConnection(connstr);
73 conn.Open();
74 using (SqlCommand cmd =
conn.CreateCommand())
75 {
76 cmd.CommandText =
procName;
77 cmd.CommandType =
CommandType.StoredProcedure;
78 cmd.Parameters.AddRange(parameters);
79 return cmd.ExecuteNonQuery();
80 }
81 }
82 }
分享一个简单的简单的SQLHelper类
标签: