编程语言

img problc

NHibernate 操作原生SQL以及查询DataTable,DataSet

发表于2008/9/28 15:12:00  2458人阅读

分类: C#

  1.         public void ExecuteNonQuery(string sql)
  2.         {
  3.             ISession session = null;
  4.             ITransaction transaction = null;
  5.             try
  6.             {
  7.                 session = SessionHelper.OpenSession();
  8.                 transaction = session.BeginTransaction();
  9.                 IDbCommand command = session.Connection.CreateCommand();
  10.                 transaction.Enlist(command);
  11.                 command.CommandText = sql;
  12.                 command.ExecuteNonQuery();
  13.                 transaction.Commit();
  14.             }
  15.             catch (Exception ex)
  16.             {
  17.                 if (transaction != null)
  18.                 {
  19.                     transaction.Rollback();
  20.                 }
  21.                 throw ex;
  22.             }
  23.             finally
  24.             {
  25.                 if (session != null)
  26.                 {
  27.                     session.Close();
  28.                 }
  29.             }
  30.         }

 

  1.         public DataSet ExecuteDataset(string sql)
  2.         {
  3.             ISession session = null;
  4.             DataSet ds = new DataSet();
  5.             try
  6.             {
  7.                 session = SessionHelper.OpenSession();
  8.                 IDbCommand command = session.Connection.CreateCommand();
  9.                 command.CommandText = sql;
  10.                 IDataReader reader = command.ExecuteReader();
  11.                 DataTable result = new DataTable();
  12.                 DataTable schemaTable = reader.GetSchemaTable();
  13.                 for (int i = 0; i < schemaTable.Rows.Count; i++)
  14.                 {
  15.                     result.Columns.Add(schemaTable.Rows[i][0].ToString());
  16.                 }
  17.                 while (reader.Read())
  18.                 {
  19.                     int fieldCount = reader.FieldCount;
  20.                     object[] values = new Object[fieldCount];
  21.                     for (int i = 0; i < fieldCount; i++)
  22.                     {
  23.                         values[i] = reader.GetValue(i);
  24.                     }
  25.                     result.Rows.Add(values);
  26.                 }
  27.                 ds.Tables.Add(result);
  28.             }
  29.             catch (Exception ex)
  30.             {
  31.                 Debug.Assert(false);
  32.             }
  33.             finally
  34.             {
  35.                 if (session != null)
  36.                 {
  37.                     session.Close();
  38.                 }
  39.             }
  40.             return ds;
  41.         }

 

阅读全文
0 0

相关文章推荐

img
取 消
img