温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - How can you retrieve the value of sys_guid() after an OracleCommand INSERT INTO

c# - 在OracleCommand INSERT INTO之后如何检索sys_guid()的值

发布于 2020-03-27 15:40:06

我想检索某个事务中包含Oracle db生成的sys_guid()的某些列的值。

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;
}

表客户有一个ORDER列,它使用SYS_GUID()创建了一个GUID,如何检索该GUID?

查看更多

查看更多

提问者
Adonis Pso
被浏览
45
Dmitry Bychenko 2020-01-31 17:43

尝试returning .. into 条款

   ...

   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;
   }  

   ...

发布
问题

分享
好友

手机
浏览

扫码手机浏览