执行sql语句函数(query表示sql查询语句,tablename也可以理解为表名,但实际的作用是映射到相对应的实体类):
1private IList ExecuteSQL( string query,string tablename)
2 {
3 IList result = new ArrayList();
4 ISessionFactoryImplementor s = (ISessionFactoryImplementor)_cfg.BuildSessionFactory();
5 IDbCommand cmd = s.ConnectionProvider.Driver.CreateCommand();
6 cmd.CommandText = query;
7 IDbConnection conn = s.OpenConnection();
8 try
9 {
10 cmd.Connection = conn;
11 IDataReader rs = cmd.ExecuteReader();
12 int j = 0 ;
13 while ( rs.Read() )
14 {
15 int fieldCount = rs.FieldCount;
16 object[] values = new Object[ fieldCount ];
17 for ( int i = 0; i < fieldCount; i ++ )
18 values[i] = rs.GetValue(i);
19 chooseEntity(result,tablename,values);
20 }
21 }
22 finally
23 {
24 s.CloseConnection(conn);
25 }
26 return result;
27 }
2 {
3 IList result = new ArrayList();
4 ISessionFactoryImplementor s = (ISessionFactoryImplementor)_cfg.BuildSessionFactory();
5 IDbCommand cmd = s.ConnectionProvider.Driver.CreateCommand();
6 cmd.CommandText = query;
7 IDbConnection conn = s.OpenConnection();
8 try
9 {
10 cmd.Connection = conn;
11 IDataReader rs = cmd.ExecuteReader();
12 int j = 0 ;
13 while ( rs.Read() )
14 {
15 int fieldCount = rs.FieldCount;
16 object[] values = new Object[ fieldCount ];
17 for ( int i = 0; i < fieldCount; i ++ )
18 values[i] = rs.GetValue(i);
19 chooseEntity(result,tablename,values);
20 }
21 }
22 finally
23 {
24 s.CloseConnection(conn);
25 }
26 return result;
27 }
在以上的代码中,函数chooseEntity就是对查询的结的转换,如下:
1private void chooseEntity(IList result,string tablename,object[] values)
2 {
3 switch(tablename)
4 {
5 case "tbl_b_AcceptConiteminfo":
6 AcceptConIteminfo accConitem = new AcceptConIteminfo(values);
7 result.Add( accConitem );
8 break;
9 }
10 }
2 {
3 switch(tablename)
4 {
5 case "tbl_b_AcceptConiteminfo":
6 AcceptConIteminfo accConitem = new AcceptConIteminfo(values);
7 result.Add( accConitem );
8 break;
9 }
10 }
在实际类的构造函数中,将数组values的值赋值到实体类中,如下:
实体类实例
ok,经过以上的处理,可以直接用来绑定数据源,当然,这样处理有不好的地方,只不过也给出了一个解决问题的方法。