Defining columns in an SQLite Database table - android

I copied an SQLite Database example, where I created a table with 3 fields/columns and inserted one record with 3 values, as follows:
>SQLiteDatabase db = openOrCreateDatabase("MyDB",MODE_PRIVATE,null);
>db.execSQL("CREATE TABLE IF NOT EXISTS FunnyNames(Email VARCHAR(255), FirstName VARCHAR(255), LastName VARCHAR(255));");
>db.execSQL("INSERT INTO FunnyNames VALUES('abath#aol.com','Anita','Bath')");
..and I received this error message
>12-28 11:35:00.896: E/SQLiteLog(8857): (1) table FunnyNames has 1 columns but 3 values were supplied
didn't I define the columns correctly?

IF NOT EXISTS only creates the table if it didn't exist. Likely you already have a table with that given name in the database file, and that table only has 1 column.
Uninstall your app or clear its data in the app manager to remove the old database file. Or add DROP TABLE IF EXISTS FunnyNames before the CREATE TABLE.

You've missed the primary key of the table. Every table needs an primary key (which is an unique id) for referencing data. Modify your create statement as follow:
CREATE TABLE IF NOT EXISTS FunnyNames(_id INTEGER PRIMARY KEY AUTOINCREMENT, Email VARCHAR(255), FirstName VARCHAR(255), LastName VARCHAR(255));

Related

SQLite db update recreate table keep values

I have a SQLite database with one table which I need to update in a new version of my database.
In the first version of the table I have a id and a txt value like this:
db.execSQL("CREATE TABLE table_name id INTEGER PRIMARY KEY AUTOINCREMENT, txt TEXT")
But in the next version of the database I wand to add a lastchanged value which must be a TIMESTAMP with default value current time in epoch which I do with (strftime('%s', 'now')).
But since I can't add a column with default current time, according to this error:
Cannot add a column with non-constant default (code 1): , while compiling: ALTER TABLE table_name ADD COLUMN edited_time TIMESTAMP DEFAULT (strftime('%s', 'now'))
I tought I could best recreate the data and copy it to the new database
// copy all data to single value something like a Cursor res maybe??
db.execSQL("DROP TABLE IF EXISTS table_name );
db.execSQL("CREATE TABLE table_name id INTEGER PRIMARY KEY AUTOINCREMENT, txt TEXT, edited_time TIMESTAMP DEFAULT (strftime('%s', 'now'))");
// now insert the values into the recreated database
But for this i need to copy all data into a new table that does not exist simultanious. Is it posible to do this without looping and having to save every value separate and then inserting them seperately again?
Yes. The general procedure is:
BEGIN;
ALTER TABLE table_name RENAME TO table_name_old;
CREATE TABLE table_name( ... );
INSERT INTO table_name(col1, ..., coln)
SELECT col1, ..., coln FROM table_name_old;
DROP table_name_old;
COMMIT;

Reset INTEGER PRIMARY KEY AUTOINCREMENT in Android

I created a table called DRINK. I inserted two rows in to it initially. When upgraded, I would like to delete both rows and reset my Primary Key to 1. I am getting the rows to delete but am not having any luck resetting the primary key. Does anybody know the syntax on how to do that or if it's even possible? Here's the function which is called from my onUpdate function:
private void updateMyDatabase(SQLiteDatabase db, int olderVersion, int newVersion){
Log.v("DatabaseHelper","UPDATE MY DATABASE");
if (olderVersion<1){
db.execSQL("CREATE TABLE DRINK (_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "NAME TEXT, "
+ "DESCRIPTION TEXT, "
+ "IMAGE_RESOURCE_ID INTEGER);");
insertDrink(db,"latte","Espresso and Steamed Milk",R.drawable.latte);
insertDrink(db, "cappuccino", "This a Cappuccino", R.drawable.cap);
}
if (olderVersion < 2){
db.execSQL("delete from DRINK");
db.execSQL("alter table AUTO_INCREMENT =1"); //*** NEED HELP HERE***
insertDrink(db, "coff", "Espresso and Steamed Milk", R.drawable.latte);
}
}
I found this piece of code online but it's not working. Thank you.
db.execSQL("alter table AUTO_INCREMENT =1");
Deleteing the rows won't reset ROWID.
SQLite documentation states:
SQLite keeps track of the largest ROWID that a table has ever held
using the special SQLITE_SEQUENCE table. 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.
This sql should do what you need:
UPDATE SQLITE_SEQUENCE SET seq = <n> WHERE name = <table>
Where n is the sequence you wish to set and table is your table name

Add the Autoincrement _id column

Hey i made a whole app without adding an autoincrement column but now i need this column to specify the max id so i created my database in my mainactivity like this.How can i modify this to add the autoincrement _id column ?
db = getActivity().openOrCreateDatabase("testDB2", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS test2(mac VARCHAR,mdp VARCHAR,obj VARCHAR);");
I don't want to create a seonc java classs only for the database because i did all the code like this.
You can't alter the sqlite table to add _id column as primary key after table created.
What you should do is creating a new table, then copy the old data to the new table.
See the faq from sqlite.org
db.execSQL("CREATE TABLE IF NOT EXISTS test2(autoincrement_id INTERGER PRIMARY KEY AUTOINCREMENT,mac VARCHAR,mdp VARCHAR,obj VARCHAR);");
only primary key can be autoincrement

Using different IDs for multiple table in SQLITE

I am using SQLite to work on an android application. What I have learned so far is that a table made in SQLite requires a column called _id. So, for instance, to create a table, I use the following SQL Statement:
CREATE TABLE IF NOT EXISTS Semesters(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
semester_name TEXT,
is_current TEXT
GPA REAL);
However, now if I want to create a seperate table in the same database, what would I name the primary key column? For instance, this is the table I want to create:
CREATE TABLE IF NOT EXISTS Classes(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
course_name TEXT);
Now, both the semesters table and the courses table have a column called _id, and if I want to make a foreign key reference to the _id column in the semesters table, I will have to call it by the table name. Is there any way to make this simpler by using different names for ids?
Thanks.
For example, you make a third table and want to use both primary keys from your tables as foreign keys:
CREATE TABLE ClassSemester(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
semester_id INTEGER,
class_id INTEGER,
FOREIGN KEY(semester_id) REFERENCES Semesters(_id),
FOREIGN KEY(class_id) REFERENCES Classes(_id)
);
More details in here:
http://www.sqlite.org/foreignkeys.html

Android SQLite auto increment

I currently have a table called User which has a id column which is created as
'INTEGER PRIMARY KEY'
Lets say I have created two users so the table has id 1 and 2
If I delete the second user and create a third the id is 2, I need this to be 3
So it seems Android is selecting the next available id, how can I change this to its more like a sequence number?
Regards
Make it INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL. Here's what the docs say:
If a column has the type INTEGER PRIMARY KEY AUTOINCREMENT then... the ROWID chosen
for the new row is at least one larger than the largest ROWID that has
ever before existed in that same table.
The behavior implemented by the AUTOINCREMENT keyword is subtly
different from the default behavior. With AUTOINCREMENT, rows with
automatically selected ROWIDs are guaranteed to have ROWIDs that have
never been used before by the same table in the same database. And the
automatically generated ROWIDs are guaranteed to be monotonically
increasing.
SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto incrementing it.
The keyword AUTOINCREMENT can be used with INTEGER field only.
Syntax:
The basic usage of AUTOINCREMENT keyword is as follows:
CREATE TABLE table_name(
column1 INTEGER AUTOINCREMENT,
column2 datatype,
column3 datatype,
.....
columnN datatype,
);
For Example See Below:
Consider COMPANY table to be created as follows:
sqlite> CREATE TABLE TB_COMPANY_INFO(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);
Now, insert following records into table TB_COMPANY_INFO:
INSERT INTO TB_COMPANY_INFO (NAME,AGE,ADDRESS,SALARY)
VALUES ( 'MANOJ KUMAR', 40, 'Meerut,UP,INDIA', 200000.00 );
Now Select the record
SELECT *FROM TB_COMPANY_INFO
ID NAME AGE ADDRESS SALARY
1 Manoj Kumar 40 Meerut,UP,INDIA 200000.00
If speaking for ANDROID, yes, above answers are correct, except naming of the id column.
database.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " ( rowid INTEGER PRIMARY KEY AUTOINCREMENT, Raqam VARCHAR, ChandBor INT(3));");
It looks like in Android it should be named as 'rowid'.
And with Cursor you need to instantiate it like:
Cursor cursorLcl = database.rawQuery("SELECT *," + TableName + ".rowid AS rowid" + " FROM " +
TableName, null);
Otherwise it didnt work for me. I don't know why it so.
Just remember for android when writing tot the database (ie. executing),
do
INSERT INTO TABLE_NAME (param1name, param2name) VALUES (param1,param2)
and there is no need to add a place holder for the auto increment. It will add it by itself when adding a record. If you do not declare the params that you will put in, you will get the error x amount of variables expected and you only gave x-1, and this is because you are not supposed to give any place holding value for the auto increment column

Categories

Resources