这是从表中读取数据然后插入表中的正确方法吗?
我正在尝试读取最大数字或rec_id来创建seq列+1以将我的数据记录插入到同一个表中
//Opening the connection with Oracle Database
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
//Create the oracle statment and insert data into oracle database
OracleCommand cmd1 = new OracleCommand();
cmd1.Connection = conn;
cmd1.CommandText = "SELECT NVL (MAX (rec_id), 0) + 1 FROM backup_check";
OracleDataReader dr = cmd1.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
conn.Dispose();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
//OracleTransaction trans = conn.BeginTransaction(); -- add rollback in case of transaction not complate for some reason
cmd.CommandText = "insert into my table(" + "'" + v_rec_id + "'" + ",OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null," + "'" + keyword + "'" + ",'0','abc',sysdate)";
cmd.ExecuteNonQuery();
//Closing the connection with oracle databae
conn.Dispose();
答案 0 :(得分:1)
首先,您应该忘记使用MAX函数来检索要插入“所谓的自动增量列”的下一个值。问题产生于这样一个事实,即在一台机器上运行的代码无法阻止另一台机器上的另一个用户与您的机器同时执行相同的代码。这可能导致两个用户都收到相同的MAX结果,从而创建无效的重复密钥。
在Oracle中,您应该将表标记为主键为Microsoft Console Reference(REC_ID)
像这样的东西(现在写在这里没有经过测试......)
CREATE TABLE myTable
(
rec_id NUMBER PRIMARY KEY
.... other columns follow
);
CREATE SEQUENCE myTable_seq MINVALUE 1 START WITH 1 INCREMENT BY 1 CACHE 20;
CREATE OR REPLACE TRIGGER myTable_trg
BEFORE INSERT ON myTable
for each row
begin
select myTable_seq.nextval into :new.rec_id from dual;
end;
此时,当您尝试插入新记录时,触发器会启动并计算要分配给主键的下一个值。
C#代码经过了简化,变成了:
string cmdText = @"insert into myTable
(OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)
values(null,:keyw,'0','abc',sysdate)";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand(cmdText, conn))
{
conn.Open();
//using(OracleTransaction trans = conn.BeginTransaction())
//{
cmd.Parameters.AddWithValue(":keyw",keyword);
cmd.ExecuteNonQuery();
// trans.Commit();
//}
}
之前无需读取任何内容,命令文本未连接,避免SQL注入,关闭和处理将自动从使用块退出....