如何使用Sqlite获取iPhone上父对象的密钥

时间:2022-08-28 07:30:39

A very simple example I am trying to create as I grasp iPhone App programming.

我正在尝试创建一个非常简单的示例,因为我掌握了iPhone App编程。

First TableView shows the makes, selecting one takes user to different view(Can I use the same view to show models) to show models. If the models TableView, that displays the car models, allows user to add a new record, how and where do I capture the primary key(pk) of the parent key(make)?

第一个TableView显示品牌,选择一个将用户带到不同的视图(我可以使用相同的视图来显示模型)来显示模型。如果显示汽车模型的模型TableView允许用户添加新记录,我如何以及在何处捕获父键(make)的主键(pk)?

Which method would I capture the primary key and how?

我将采用哪种方法捕获主键以及如何捕获?

Sqlite database:

CREATE TABLE make(pk INTEGER PRIMARY KEY, parentkey INTEGER DEFAULT 0, title TEXT);

INSERT INTO make(title) VALUES('Honda');
INSERT INTO make(title) VALUES('Toyota');
INSERT INTO make(title) VALUES('Mazda');
INSERT INTO make(title) VALUES('Nissan');

INSERT INTO make(title, parentkey) VALUES('Civic', 1);
INSERT INTO make(title, parentkey) VALUES('Accord', 1);
INSERT INTO make(title, parentkey) VALUES('Corolla', 2);
INSERT INTO make(title, parentkey) VALUES('Corona', 2);

1 个解决方案

#1


Via SQL, you can query the SQLITE_SEQUENCE table after every insert:

通过SQL,您可以在每次插入后查询SQLITE_SEQUENCE表:

SELECT seq FROM SQLITE_SEQUENCE WHERE name = 'make'

SELECT seq FROM SQLITE_SEQUENCE WHERE name ='make'

This will only work reliably if you do your inserts and this select in the same transaction, locking the table so no one else can do an insert before you get the value from the sequence table.

只有在执行插入操作并且在同一事务中选择此选项时,这才能可靠地工作,锁定表,以便在从序列表中获取值之前,没有其他人可以执行插入操作。


Using the API (and not SQL):

使用API​​(而不是SQL):

sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);

(from http://www.sqlite.org/c3ref/last_insert_rowid.html)

#1


Via SQL, you can query the SQLITE_SEQUENCE table after every insert:

通过SQL,您可以在每次插入后查询SQLITE_SEQUENCE表:

SELECT seq FROM SQLITE_SEQUENCE WHERE name = 'make'

SELECT seq FROM SQLITE_SEQUENCE WHERE name ='make'

This will only work reliably if you do your inserts and this select in the same transaction, locking the table so no one else can do an insert before you get the value from the sequence table.

只有在执行插入操作并且在同一事务中选择此选项时,这才能可靠地工作,锁定表,以便在从序列表中获取值之前,没有其他人可以执行插入操作。


Using the API (and not SQL):

使用API​​(而不是SQL):

sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);

(from http://www.sqlite.org/c3ref/last_insert_rowid.html)