Home  >  Article  >  Database  >  关于各种数据库 Insert时同时取到Id的操作_MySQL

关于各种数据库 Insert时同时取到Id的操作_MySQL

WBOY
WBOYOriginal
2016-06-01 13:12:011348browse

对数据库的操作,在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.000711             ) 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[];

 请注意上面代码中的 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             }

 

 

MySql:   

暂时缺少,如有网友有可靠的方法,请在评论中联系我。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn