asp.net数据库操作类(二)

第二版的数据库访问类出炉了:

 C# Code 
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
 
public class OledbDataService1:IDisposable
    {
        
public OledbDataService1(string conStr)
        {
            ConnectionString = conStr;
        }
        
//[关闭]
        public void Close()
        {
            
if (_Command != null)
            {
                
if (_Command.Connection.State != ConnectionState.Closed)
                    _Command.Connection.Close();
            }
        }
        
public void Dispose()
        {
            Close();
            
if (_Command != null)
            {
                _Command.Connection.Dispose();
                _Command.Dispose();
            }
        }
        
//连接字符串
        public string ConnectionString
        {
            get;
            
private set;
        }
        
//sql执行器
        private OleDbCommand _Command;
        
public OleDbCommand Command
        {
            get
            {
                
if (_Command == null)
                {
                    _Command = 
new OleDbConnection(ConnectionString).CreateCommand();
                }
                
return _Command;
            }
        }
        
//数据库适配器
        private OleDbDataAdapter _Adapter;
        
public OleDbDataAdapter Adapter
        {
            get
            {
                
if (_Adapter == null)
                {
                    _Adapter = 
new OleDbDataAdapter(Command);
                }
                
return _Adapter;
            }
        }
        
//得到查询结果
        public DataTable Execute(string sql)
        {
            Command.CommandText = sql;
            DataTable db = 
new DataTable();
            Adapter.Fill(db);
            
return db;
        }
        
//检查Connection打开状态
        protected void CheckConnectionState()
        {
            
if (Command.Connection.State != ConnectionState.Open)
                Command.Connection.Open();
        }
    }

调用方法如下:

 C# Code 
1
2
3
4
5
6
 
using (var db = Common.GetDataServicetest("AccessConStr""dbPath"))
{
    
string sql = "Select top 1 Dept_No from Dept_No";
    DataTable dt = db.Execute(sql);
    Console.WriteLine(
"Name = " + dt.Rows[0][0]);
}

通过实现IDisposale接口可以手动调用资源清理方法来进行资源回收,using(...){...}using关键字在C#中主要有几个用途:

  1.引用命名空间,以减少输入

  2.为命名空间创建别名

  3.用于在限定范围结束后自动释放资源,如自动释放数据连接、事务句柄等

因此在执行完数据操作后,可以自动释放数据库。同时可以在一次数据库的操作中多次执行操作,避免重复打开数据库连接的消耗。

posted on 2013-09-01 12:11  酷^$^喾  阅读(183)  评论(0编辑  收藏  举报

导航