1 public class DBHelper
2 {
3 //数据库连接属性,从config配置文件中获取连接字符串connectionString
4 public static string Connection = ConfigurationManager.AppSettings["ConnectionString"].ToString();
5 //数据库连接字符串
6
7
8 /// <summary>
9 /// 创建连接对象 暂时连接为空
10 /// </summary>
11 private static SqlConnection con = null;
12
13 #region 获取连接对象,使用if语句判断连接的条件。
14 //获取连接对象,使用if语句判断连接的条件。
15 public static SqlConnection GetConnection()
16 {
17 if (con == null || con.ConnectionString == "")//获取用于打开数据库的字符串
18 {
19 con = new SqlConnection(Connection);
20 // con = new SqlConnection(Connection);
21 }
22 return con;
23 }
24 #endregion
25
26
27 /// <summary>
28 /// ///打开连接和关闭连接。通过判断状态来实现,这里需要添加using System.Data来引用状态。
29 /// </summary>
30 #region 打开数据库连接
31 //打开数据库连接
32 public static void OpenConnection()
33 {
34 ///判断连接是否已经创建
35 if (con != null)
36 {
37 if (con.State == ConnectionState.Closed)
38 {
39 con.Open();
40
41 }
42 }
43 }
44
45 #endregion
46
47 #region 关闭数据库连接
48 //关闭数据库连接
49 public static void CloseConnection()
50 {
51 ///判断连接是否已经创建
52 if (con != null)
53 {
54 ///判断连接的状态是否打开
55 if (con.State == ConnectionState.Open)
56 {
57 con.Close();
58 }
59
60 }
61 }
62 #endregion
63
64 #region 查询多行多列的值
65
66 //查询多行多列的值
67 public static SqlDataReader ExecuteReader(string sql, CommandType type = CommandType.Text, params SqlParameter[] para)
68 {
69 //创建连接对象
70 SqlConnection con = GetConnection();
71 //打开连接
72 OpenConnection();
73 //创建命令对象
74 SqlCommand com = new SqlCommand();
75 //指定命令类型
76 com.CommandType = type;
77 //指定命令的参数
78 com.Parameters.AddRange(para);
79 //执行查询,用于查询。
80 SqlDataReader dr = com.ExecuteReader();
81 //关闭连接
82 CloseConnection();
83 return dr;
84
85 }
86 #endregion
87
88
89 #region 动作查询
90
91 public static int ExecuteNonquery(string sql, CommandType type = CommandType.Text, params SqlParameter[] para)
92 {
93 //创建命令对象
94 SqlConnection con = new SqlConnection();
95 //打开连接
96 OpenConnection();
97 //创建命令对象
98 SqlCommand com=new SqlCommand();
99 //指定命令类型
100 com.CommandType = type;
101 //指定命令的参数
102 com.Parameters.AddRange(para);
103 //执行查询,用于更新,删除,插入。
104 int dt = com.ExecuteNonQuery();
105 //关闭连接
106 CloseConnection();
107
108 return dt;
109 }
110
111 #endregion
112 }