1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace GFAMS
{
class DBHelper
{
//数据库连接字符串
private static string connStr = "Data Source=.;Initial Catalog=数据库名;Integrated Security=True";

/// <summary>
/// 内部数据连接对象
/// </summary>
private static SqlConnection Conn = null;

/// <summary>
/// 内部实例对象
/// </summary>
private static DBHelper Instance = null;

private DBHelper()
{

}

/// <summary>
/// 静态方法,获取数据库连接实例
/// </summary>
/// <returns>数据库连接实例</returns>
public static DBHelper GetInstance()
{
if (DBHelper.Instance == null)
{
DBHelper.Instance = new DBHelper();
}
return DBHelper.Instance;
}

/// <summary>
/// 初始化数据库连接
/// </summary>
public void InitConnection()
{
//如果连接对象不存在,则创建连接
if (Conn == null)
Conn = new SqlConnection(connStr);
//如果连接对象关闭,则打开连接
if (Conn.State.Equals(ConnectionState.Closed))
Conn.Open();
//如果连接中断,则重启连接
if (Conn.State.Equals(ConnectionState.Broken))
{
Conn.Close();
Conn.Open();
}
}

/// <summary>
/// 查询、获取 DataReader
/// </summary>
/// <param name="sqlStr">Sql语句</param>
/// <returns>SqlDataReader 数据集</returns>
public SqlDataReader GetDataReader(string sqlStr)
{
InitConnection();
SqlCommand cmd = new SqlCommand(sqlStr, Conn);
//CommandBehavior.CloseConnection 命令行为:当 DataReader 对象被关闭时,自动关闭占用的连接对象
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}

/// <summary>
/// 查询、获取 DataTable
/// </summary>
/// <param name="sqlStr">Sql语句</param>
/// <returns>DataTable 数据表</returns>
public DataSet GetDataSet(string sqlStr)
{
InitConnection();
DataSet ds = new DataSet();
SqlDataAdapter dap = new SqlDataAdapter(sqlStr, Conn);
dap.Fill(ds);
Conn.Close();
return ds;
}

/// <summary>
/// 执行增删改
/// </summary>
/// <param name="sqlStr">Sql语句</param>
/// <returns>受影响行数</returns>
public int ExecuteNonQuery(string sqlStr)
{
InitConnection();
SqlCommand cmd = new SqlCommand(sqlStr, Conn);
int rows = cmd.ExecuteNonQuery();
Conn.Close();
return rows;
}

/// <summary>
/// 执行聚合函数
/// </summary>
/// <param name="sqlStr">Sql语句</param>
/// <returns>Object对象</returns>
public object ExecuteScalar(string sqlStr)
{
InitConnection();
SqlCommand cmd = new SqlCommand(sqlStr, Conn);
object result = cmd.ExecuteScalar();
Conn.Close();
return result;
}
}
}

这是一篇过去很久的文章,其中的信息可能已经有所发展或是发生改变。