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
Related
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));
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
I have couple of tables which will have new data every time the user logs into the application. I have a column KEY_ROWID which is autoIncrement. I want it to always start with 1.
I tried truncating the table before new data is inserted. I get an error:
"android.database.sqlite.SQLiteException: near "TRUNCATE": syntax
error (code 1): , while compiling: TRUNCATE TABLE StaffListTable"
Sugestions much appreciated.
private static final String CREATE_TABLE_STAFFLIST = "CREATE TABLE " + TABLE_STAFFLIST + " ("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_STAFFID + " TEXT NOT NULL, "
+ KEY_STAFFNAME + " TEXT NOT NULL);";
Its very simple, since you are truncating the table values I understand you don't have to secure them or take a back up. In such a case just dropping the table will do the trick.
In onUpdate() method, write
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE); //and call onCreate again
onCreate(db);
Let me know if you need anything else. Happy coding. :)
There's no TRUNCATE in sqlite. You can use DROP to delete tables if you really need to.
There are two ways to effect a truncate (which SQLite doesn't have). You can either DROP and then CREATE as per other answers here.
Alternatively you can do a DELETE to empty the table and then remove the entry for the table from sqlite_sequence:
DELETE FROM sqlite_sequence
WHERE name = 'table_name'
sqlite_sequence holds the last used autoincrement value for tables with such columns. Removing the row for a given table will make the autoincrement key start at 1 again.
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
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