I have a databse with three tables.
The first table is something like:
_id user
The second table:
_id route user_id
and user_id is exactly the _id from the first table.
So when I insert in the first tabel a new record,I should keep the _id in order to insert it
in the second table.But how could I keep something that is autoincremented and given by the database?:-S
The SQLiteDatabase has an insert() method, which returns the _id you are looking for.
There may be a better way, but you could grab (query for) the _id field right after you do your commit to the first table. Then you will have the user_id for use in the second table.
Related
I need to retrieve the id of the row inserted just now. ie, i have a table for words and a table for meaning. i need the wordId of the word i insert in the table for words and that wordId is used for inserting the meaning in meaning table. Can anyone help me out??
I thought i could use trigger and tried the trigger:
"CREATE TRIGGER IF NOT EXISTS word_insert_trigger AFTER INSERT ON tb_words BEGIN select NEW.word_id from tb_words; END;"
like this. i tried this in sqlite dbbrowser. but it didn't work out.
i need the row id when i insert a row like this :"insert into tb_words(word_name) values('test');"
How can i do that without using "SELECT last_insert_rowid()"? like in the following link:
How to retrieve the last autoincremented ID from a SQLite table?
No need for a trigger. Use the SQliteDatabase insert method. It returns the id (as a long) (more correctly it returns the rowid and assuming that the word_id column has been defined as an alias of the rowid column, then the returned value will be the value assigned to the word_id column).
An alias of the rowid column is defined if word_id INTEGER PRIMARY KEY is coded (the AUTOINCREMENT key may be used BUT in generally should not be used).
You may wish to read SQLite AUTOINCREMENT and/or Rowid Tables
Instead of something like :-
db.execsql("insert into tb_words(word_name) values('test');");
You would use something like :-
ContentValues cv = new ContentValues();
cv.put("word_name","test");
long word_id = db.insert("tb_words",null,cv);
I wanted to create two related tables. My query that is creating tables looks like this:
static final String SQL_CREATE_TABLE_LISTS =
"CREATE TABLE Lists(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT);";
static final String SQL_CREATE_TABLE_ITEMS =
"CREATE TABLE Items(IdList INTEGER, ItemName TEXT, FOREIGN KEY(IdList) REFERENCES Lists(Id));";
I want now insert and select some data from table Items, but I do not know how the query should looks like. Lets say I have one record in table Lists: id=1 and name=element1. And now I want to add 3 records to table Items, so IdList will be 1, and name will be item1, item2 and item3. How the inserting query will be like? And then, if I want to take for ex. all Names from table Items that its IdList is 1, how the select query will be like? Thanks.
A FOREIGN KEY is a Constraint (Rule that MUST be followed), it does not define a relationshop/link for extracting data. In other words it is saying if the rule is not met then a row cannot be inserted. It is not saying every time you access either of the tables that they are automatically linked.
When inserting you you would insert the Lists first, you would then insert the Items using(checking) the available Lists. You cannot insert into/across multiple tables directly.
You need to use JOIN when querying the data as FOREIGN KEY is just a rule (constraint) that is checked when inserting a row.
So you would do something along the line of:-
SELECT Lists.Id, Lists.Name, Items.ItemName FROM Lists JOIN Items ON Lists.Id = Items.IdList
I want to add a column to a table in case the column doesn't exist,but SQLite doesn't seem to update the column list in Android
currently i'm using:
DB.execSQL("alter table "+table_name+" add column "+column_name+" text");
DB.rawQuery("select * from "+table_name+" limit 1",null).getColumnNames();
but the string list returned from "getColumnNames" does not contain the column I just created, so when I check again for the same column, it understands the column doesn't exist and tries to create it again, which causes a "duplicated column" exception
Thanks in advance for any help,this is my first question in SO :)
You need to increase the database number, which will call onUpgrade on your next app launch. In your onUpgrade method, you run the SQLite command to alter the table.
See here for some examples.
Try to discard the result of the first query after the "alter table" command and use the result of a second query. It worked for me.
I have 3 tables: users, albums, photos. User can have albums, each album have photos.
I want add at table [photos] new column userId with correct data.
I want not only add empty userId column, but this column must be have value from table albums: userId.
How I can easy todo this?
There is two tasks to do :
First, add the column to the table.
Once done, you will want to populate userId column. But, in SQLite, you cannot perform a JOIN in an UPDATE statement.
So you should cut it in four steps (I assume there is only 3 fields in your photos table, adapt it to your one).
First create a temporary table which will contain the final datas
CREATE TABLE photos_temp (
id INTEGER PRIMARY KEY AUTOINCREMENT,
albumId INTEGER NOT NULL,
userId INTEGER NOT NULL
);
Then, populate the temporary table
INSERT INTO photos_temp(id, albumId, userId)
SELECT photos.id as id,
photos.albumId as albumId,
albums.userId as userId
FROM photos
INNER JOIN albums ON photos.albumId = albums.id;
Then, remove the original table
DROP TABLE photos;
Finally, rename the previous table
ALTER TABLE photos_temp RENAME TO photos;
Sorry, but no easier way to do this.
I have a doubt that if i delete the table using following statements,
SQLiteDatabase db = this.getWritableDatabase();
db.delete(date_difference, null, null);
then if i'm inserting a row as a fresh and first record into the table, will the id primary key auto increment of the records starts from 1 ?
If no ROWID is specified on the insert, or if the specified ROWID has
a value of NULL, then an appropriate ROWID is created automatically.
The usual algorithm is to give the newly created row a ROWID that is
one larger than the largest ROWID in the table prior to the insert.
If the table is initially empty, then a ROWID of 1 is used. If the largest ROWID is equal to the largest possible integer
(9223372036854775807) then the database engine starts picking positive
candidate ROWIDs at random until it finds one that is not previously
used.
So yes, after you delete the table, IDs will start from 1
http://www.sqlite.org/autoinc.html
The documentation provided states that that delete method is a:
Convenience method for deleting rows in the database.
The syntax is:
int delete(String table, String whereClause, String[] whereArgs)
Therefore it won't start from 1 again. It'll continue on from the last increment. If you deleted the whole table, then re-created it, the increment would begin at 1.
SQLite keeps track of the largest ROWID that a table has ever held using an internal table named "sqlite_sequence". The sqlite_sequence table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created**.
The content of the sqlite_sequence table can be modified using ordinary UPDATE, INSERT, and DELETE statements**. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.
So when you delete your table and you re-create it, you should make the SQLITE_SEQUENCE restart from 0.
You should do something like this :
Delete from date_difference;
Delete from sqlite_sequence where name='date_difference';
Care because the field 'table name' in where clause is case sensitive.
Read this for more informations.
Define the primary key field as
INTEGER PRIMARY KEY AUTOINCREMENT DEFAULT 1
Then remove the code if you are doing insertion of any value for the primary key field like following
values.put(KEY_PRIMARY, object.getIntegerValue());