對數據庫的操作,在Insert的同時獲取到Id,保證原子性操作。而不是,先取Id,然後再插入到數據庫等操作。
Oracle:
使用Oracle自帶的 Returning into 語句,具體代碼示例如下:
1 sql = @"INSERT INTO KEYWORD(KEYWORD_ID,SITE_ID,KEYWORD_NAME,STATUS,SOURCE,CREATE_TIME,LAST_CHANGED) 2 VALUES 3 ( 4 KEYWORD_SEQ.nextVal, 5 :SITE_ID, 6 :NAME, 7 1, 8 :Source, 9 SYSDATE, 10 SYSDATE+0.0007 11 ) RETURNING KEYWORD_ID into :Key_ID"; 12 13 com.CommandText = sql; 14 //com.Parameters.Add(new OracleParameter(":ID", OracleDbType.Int64, allKeyWords.Select(n => n.Keyword_Id).ToArray(), ParameterDirection.Input)); 15 com.Parameters.Add(new OracleParameter(":SITE_ID", OracleDbType.Int64, allKeyWords.Select(n => n.Site_Id).ToArray(), ParameterDirection.Input)); 16 com.Parameters.Add(new OracleParameter(":NAME", OracleDbType.NVarchar2, allKeyWords.Select(n => n.Keyword_Name).ToArray(), ParameterDirection.Input)); 17 com.Parameters.Add(new OracleParameter(":Source", OracleDbType.NVarchar2, allKeyWords.Select(n => n.Source).ToArray(), ParameterDirection.Input)); 18 var outputIdParm = new OracleParameter(":Key_ID", OracleDbType.Int32, ParameterDirection.Output); 19 com.Parameters.Add(outputIdParm); 20 21 com.ExecuteNonQuery(); 22 23 var allKeyWordIds = outputIdParm.Value as OracleDecimal[]; View Code請注意上面代碼中的 Returning 語句,以及最後參數的outPut。
SqlServer:使用SqlServer自帶的 @@IDENTITY 關鍵字,具體代碼示例如下:
1 var cmd = dbMenloFramework.CreateCommand("insert into syslog (Thread) values('test') SELECT @@IDENTITY AS Id"); 2 using(var read = dbMenloFramework.ExecuteDataReader(cmd)){ 3 read.Read(); 4 Console.WriteLine(read[0].ToString()); 5 } View Code
MySql:
暫時缺少,如有網友有可靠的方法,請在評論中聯系我。