我們將談到C#綁定變量和匿名塊獲取獲取序列當前值,首先需要在Oracle中進行一系列的操作,接下來是C#綁定變量的具體操作。
1.在Oracle中建立表、序列、觸發器:
SQL> create table TESTTAB
(
ID NUMBER,
NAME VARCHAR2(10)
);
表被創建
SQL> create sequence TESTTABSEQ
minvalue 1
maxvalue 999999999999999999999999999
start with 1
increment by 1
cache 20;
序列被創建
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;
/
觸發器被創建
2.主要的C#綁定變量代碼:
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();
}
}