Reputation: 1740
I am new to android sqlite.
Problem:
Create a table with three columns(namely column1,column2 and column3) all of type TEXT .Column1 and Column2 should together form a composite primary key.Also,this table will be used by CursorAdapter. So creating an _id
field becomes necessary.
Till Now:
Able to create a table without _id with column1 and column2 as PK using below query:
CREATE TABLE Test ( column1 TEXT, column2 TEXT, column3 TEXT, PRIMARY KEY(column1,column2 ));
Able to create a table with _id as AUTOINCREMENT
CREATE TABLE Test ( _id INTEGER PRIMARY KEY AUTOINCREMENT, column1 TEXT, column2 TEXT, column3 TEXT);
But I am unable to create the combination of both.
I have tried the below queries and both give errors:
1> CREATE TABLE Test ( _id INTEGER AUTOINCREMENT, column1 TEXT, column2 TEXT, column3 TEXT, PRIMARY KEY(_id ,column1,column2 ));
2>CREATE TABLE Test ( _id INTEGER , column1 TEXT, column2 TEXT, column3 TEXT, PRIMARY KEY(_id AUTOINCREMENT,column1,column2 ));
So please help me out in creating the table with the below mentioned feature i.e.
_id
autoincrement fieldUpvotes: 2
Views: 882
Reputation: 83
If you use the ROWID approach do you open yourself up to race conditions if multiple resolvers are calling your provider at once? For example let's say some app deletes row #5, shifting all the ROWIDs down by 1.. if you click to update that same row prior to your dataset being refreshed, you'll end up writing over row #6 since you're using row number and not unique IDs (IDs would prevent this since SQLiteDatabase is threadsafe).. It might be important to use unique IDs if that's true, even if it takes up one extra column.. would like to know for sure..
Upvotes: 0
Reputation: 3322
try this,
CREATE TABLE IF NOT EXISTS Test ( _id INTEGER, column1 TEXT, column2 TEXT, column3 TEXT, PRIMARY KEY(_id,column1,column2));
Upvotes: -1
Reputation: 1007369
So creating an _id AUTOINCREMENT field is mandatory.
Not exactly. The Cursor
needs an _id INTEGER
column that is unique. You could use an INTEGER PRIMARY KEY
if you had one. If not, use ROWID
:
SELECT ROWID AS _id, ...
where ...
is the rest of your query. This allows you to leave your table schema alone, yet still satisfy the CursorAdapter
requirement.
(and how I wish Google had pointed this out back in 2008...)
Upvotes: 3