获取最后插入的ID与SQLite.NET在C# [英] Getting the Last Insert ID with SQLite.NET in C#
问题描述
我有一个不是那么简单的解决方案,一个简单的问题...我目前插入一些数据到这样的数据库:
kompenzacijeDataSet.KompenzacijeRow kompenzacija = kompenzacijeDataSet.Kompenzacije.NewKompenzacijeRow();
kompenzacija.Datum = DateTime.Now;
kompenzacija.PodjetjeID = stranka.id;
kompenzacija.Znesek = Decimal.Parse(tbZnesek.Text);
kompenzacijeDataSet.Kompenzacije.Rows.Add(kompenzacija);
kompenzacijeDataSetTableAdapters.KompenzacijeTableAdapter kompTA =新kompenzacijeDataSetTableAdapters.KompenzacijeTableAdapter();
kompTA.Update(this.kompenzacijeDataSet.Kompenzacije);
this.currentKompenzacijaID = LastInsertID(kompTA.Connection);
最后一行是很重要的。为什么我提供连接?那么有一个叫SQLite的功能的 last_insert_rowid(),您可以调用并获得最后插入的ID。问题是,它被绑定到一个连接和.NET似乎被重新打开和关闭对每个数据集的操作连接。我想,要得到一个表适配器会改变事物的连接。但事实并非如此。
有没有人知道如何解决这个问题?也许从哪里得到的持续连接?或者也可以是更优雅?
感谢您
编辑:
这也与交易的问题,我需要在同一个连接,如果我想使用的交易,这样也有一个问题...
选择last_insert_rowid();
和则需要执行它作为一个标量查询。
SQL字符串= @选择last_insert_rowid();
长lastId =(长)command.ExecuteScalar(SQL); //需要类型转换,因为`ExecuteScalar`返回一个对象。
I have a simple problem with a not so simple solution... I am currently inserting some data into a database like this:
kompenzacijeDataSet.KompenzacijeRow kompenzacija = kompenzacijeDataSet.Kompenzacije.NewKompenzacijeRow();
kompenzacija.Datum = DateTime.Now;
kompenzacija.PodjetjeID = stranka.id;
kompenzacija.Znesek = Decimal.Parse(tbZnesek.Text);
kompenzacijeDataSet.Kompenzacije.Rows.Add(kompenzacija);
kompenzacijeDataSetTableAdapters.KompenzacijeTableAdapter kompTA = new kompenzacijeDataSetTableAdapters.KompenzacijeTableAdapter();
kompTA.Update(this.kompenzacijeDataSet.Kompenzacije);
this.currentKompenzacijaID = LastInsertID(kompTA.Connection);
The last line is important. Why do I supply a connection? Well there is a SQLite function called last_insert_rowid() that you can call and get the last insert ID. Problem is it is bound to a connection and .NET seems to be reopening and closing connections for every dataset operation. I thought getting the connection from a table adapter would change things. But it doesn't.
Would anyone know how to solve this? Maybe where to get a constant connection from? Or maybe something more elegant?
Thank you.
EDIT:
This is also a problem with transactions, I would need the same connection if I would want to use transactions, so that is also a problem...
select last_insert_rowid();
And you will need to execute it as a scalar query.
string sql = @"select last_insert_rowid()";
long lastId = (long)command.ExecuteScalar(sql); // Need to type-cast since `ExecuteScalar` returns an object.
这篇关于获取最后插入的ID与SQLite.NET在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!