SQLite数据库中获取新插入数据的自增长ID
时间:2021-07-01 10:21:17
帮助过:2人阅读
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;
}
}
}
SQLite数据库中获取新插入数据的自增长ID
标签: