简体   繁体   English

如何使用Android和SQLite将表的最新row_id插入到不同的表中

[英]How to insert the latest row_id of a table into a different table using Android and SQLite

I understand the title may sound confusing, but the goal is very clear: 我理解这个标题可能听起来令人困惑,但目标很明确:

I am building an application that requires two tables: tracks and waypoints. 我正在构建一个需要两个表的应用程序:轨道和航点。

A user enters the track name via a textfield and the table generates an ID under track_id. 用户通过文本字段输入曲目名称,该表在track_id下生成ID。

in the waypoints table there is a column called track_id_fk. 在航点表中有一个名为track_id_fk的列。 When the OnLocationChanged() method is called, the longitude and latitude is entered into the table, along with the time. 调用OnLocationChanged()方法时,会将经度和纬度与时间一起输入到表中。

I want to add the track_id of the newest track entry in the track table to the track_id_fk column in the waypoints table. 我想将轨道表中最新轨道条目的track_id添加到航点表中的track_id_fk列。

I am using the following code: 我使用以下代码:

SQLiteDatabase db = waypoints.getWritableDatabase();
        ContentValues waypointvalues = new ContentValues();
        waypointvalues.put(LONGITUDE, loc.getLongitude());
        waypointvalues.put(LATITUDE, loc.getLatitude());
        waypointvalues.put(TIME, System.currentTimeMillis());
        waypointvalues.put(TRACK_ID_FK, "last inserted trackid");
        db.insertOrThrow(TABLE_NAME, null, waypointvalues);

I am unsure as to what the value should be where "last inserted trackid" is. 我不确定“最后插入的trackid”的值应该是什么。

Thanks 谢谢

insertOrThrow Returns the row ID of the newly inserted row, or -1 if an error occurred insertOrThrow返回新插入行的行ID,如果发生错误, 返回-1

    SQLiteDatabase db1 = tracks.getWritableDatabase();
    ContentValues tracksvalues = new ContentValues();
    tracksvalues.put(COL1, '1');
    tracksvalues.put(COL2, '2');
    Long insertid=db1.insertOrThrow(TABLE_NAME1, null, tracksvalues);

    if (insertid!=-1) {

        SQLiteDatabase db2 = waypoints.getWritableDatabase();
        ContentValues waypointvalues = new ContentValues();
        waypointvalues.put(LONGITUDE, loc.getLongitude());
        waypointvalues.put(LATITUDE, loc.getLatitude());
        waypointvalues.put(TIME, System.currentTimeMillis());
        waypointvalues.put(TRACK_ID_FK, insertid);
        db2.insertOrThrow(TABLE_NAME2, null, waypointvalues);

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM