SQLite数据库中有一有列名为ID的自增列,项目需求要在向数据库在插入新数据的同时返回新插入数据行的ID。
我这里用事务,把插入和查询语句通过ExecuteReader一起提交,返回DbDataReader。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
public bool Insert(string topic, string key, string value, out int id) { DbProviderFactory factory = SQLiteFactory.Instance; using (DbConnection conn = factory.CreateConnection()) { conn.ConnectionString = _connectionString; conn.Open(); DbCommand cmdInsert = conn.CreateCommand(); cmdInsert.Parameters.Add(cmdInsert.CreateParameter()); cmdInsert.Parameters.Add(cmdInsert.CreateParameter()); cmdInsert.Parameters.Add(cmdInsert.CreateParameter()); DbTransaction trans = conn.BeginTransaction(); try { cmdInsert.CommandText = "INSERT INTO [{0}] ([Topic],[Key],[Value]) VALUES (?,?,?);SELECT LAST_INSERT_ROWID() FROM [{0}]"; cmdInsert.CommandText = string.Format(cmdInsert.CommandText, _messageTableName); cmdInsert.Parameters[0].Value = topic; cmdInsert.Parameters[1].Value = key; cmdInsert.Parameters[2].Value = value; DbDataReader reader = cmdInsert.ExecuteReader(); trans.Commit(); if (reader.Read()) { id = int.Parse(reader[0].ToString()); reader.Close(); return true; } else { SAEC_Log4net.Log.Error("insert message to db fail"); id = 0; return false; } } catch (Exception e) { trans.Rollback(); SAEC_Log4net.Log.Error(e.ToString()); id = 0; return false; } } } |