简体   繁体   中英

How can you retrieve the value of sys_guid() after an OracleCommand INSERT INTO

I want to retrieve the value of a certain column that contain an Oracle db generated sys_guid() within a transaction.

public string GetGUID(OracleConnection connection) 
{ 
  string guid = "";
  connection.Open();
  OracleCommand cmd = new OracleCommand();
  OracleTransaction transaction;
  transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);
  cmd.Transaction = transaction;
  cmd.Connection = connection;
  try
  {
   cmd = connection.CreateCommand();
   cmd.CommandText = "INSERT INTO CUSTOMERS (NAME,DETAILS) VALUES (:nm, :dts)";
   cmd.Parameters.Add("nm", OracleDbType.VarChar);
   cmd.Parameters["nm"].Value = name;
   cmd.Parameters.Add("dts", OracleDbType.VarChar);
   cmd.Parameters["dts"].Value = details;
   cmd.Prepare();
   OracleDataReader reader = cmd.ExecuteReader();
   while (reader.Read())
   {

   }
   reader.Close();
   transaction.Commit();
  }
  catch (Exception e)
  {
      transaction.Rollback();
      Console.WriteLine(e.Message);
      }
 return guid;
}

Table CUSTOMERS have a column ORDER that creates a guid with SYS_GUID(), how can I retrieve that guid?

try returning .. intoclause eg

   ...

   using (OracleCommand cmd = connection.CreateCommand()) {
     cmd.CommandText = 
       @"INSERT INTO CUSTOMERS (
           NAME,
           DETAILS) 
         VALUES (
           :nm, 
           :dts)
         RETURNING 
           ""ORDER"" INTO :orderid";

     cmd.Parameters.Add("nm", OracleDbType.VarChar);
     cmd.Parameters["nm"].Value = name;
     cmd.Parameters.Add("dts", OracleDbType.VarChar);
     cmd.Parameters["dts"].Value = details;

     cmd.Parameters.Add("orderid", OracleDbType.VarChar);  
     cmd.Parameters["orderid"].Direction = ParameterDirection.Output;

     try {
       cmd.ExecuteNonQuery(); // Just execute, nothing to read
       transaction.Commit(); 

       guid = Convert.ToString(cmd.Parameters["orderid"].Value);
     }
     catch (Exception e) { //TODO: put more specific exception type
       transaction.Rollback();   
       Console.WriteLine(e.Message);     
     } 

     return guid;
   }  

   ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM