Simple analysis of C # binding variables and anonymous blocks getting the current value of a sequence

Source: Internet
Author: User

We'll talk about C # binding variables and anonymous blocks to get the current value of the sequence, we first need to do a series of operations in Oracle, followed by the concrete operation of C # binding variables.

1. Create tables, sequences, triggers in Oracle:

SQL> create table TESTTAB
(
  ID   NUMBER,
  NAME VARCHAR2(10)
);

Table is created

SQL> create sequence TESTTABSEQ
    minvalue 1
    maxvalue 999999999999999999999999999
   start with 1
    increment by 1
    cache 20;

Sequence is created

SQL> create or replace trigger Tr_testtabid
   before insert on testtab for each row

    begin
     SELECT TESTTABSEQ.NEXTVAL into :NEW.id from dual;
     end Tr_testtabid;
    /

Triggers are created

2. Main C # binding variable code:

using ORAC = System.Data.OracleClient;
private void button1_Click(object sender, System.EventArgs e)
{
 try
 {

  string str_Sql = @"begin insert into testtab(name) values('test'); select TESTTABSEQ.Currval into :ID from dual; end;";
  ORAC.OracleCommand cmd= new ORAC.OracleCommand(str_Sql,this.oracleConnection1);

  ORAC.OracleParameter parm = new ORAC.OracleParameter("ID",ORAC.OracleType.Number);
  parm.Direction = ParameterDirection.Output;
  cmd.Parameters.Add(parm);

  if(this.oracleConnection1.State == System.Data.ConnectionState.Closed)
  {
   this.oracleConnection1.Open();
  }
  cmd.ExecuteNonQuery();

  this.textBox1.Text = cmd.Parameters[0].Value.ToString();
 }
 catch(Exception ex)
 {
  MessageBox.Show("发生错误!";

 }
 finally
 {
  this.oracleConnection1.Close();
 }

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.