I have created my tables in my SQLiteOpenHelper onCreate() but receive
SQLiteException: no such table
or
SQLiteException: no such column
errors. Why?
NOTE:
(This is the amalgamated summary of tens of similar questions every week. Attempting to provide a "canonical" community wiki question/answer here so that all those questions can be directed to a good reference.)
SQLiteOpenHelper onCreate() and onUpgrade() callbacks are invoked when the database is actually opened, for example by a call to getWritableDatabase(). The database is not opened when the database helper object itself is created.
SQLiteOpenHelper versions the database files. The version number is the int argument passed to the constructor. In the database file, the version number is stored in PRAGMA user_version.
onCreate() is only run when the database file did not exist and was just created. If onCreate() returns successfully (doesn't throw an exception), the database is assumed to be created with the requested version number. As an implication, you should not catch SQLExceptions in onCreate() yourself.
onUpgrade() is only called when the database file exists but the stored version number is lower than requested in the constructor. The onUpgrade() should update the table schema to the requested version.
When changing the table schema in code (onCreate()), you should make sure the database is updated. Two main approaches:
Delete the old database file so that onCreate() is run again. This is often preferred at development time where you have control over the installed versions and data loss is not an issue. Some ways to delete the database file:
Uninstall the application. Use the application manager or adb uninstall your.package.name from the shell.
Clear application data. Use the application manager.
Increment the database version so that onUpgrade() is invoked. This is slightly more complicated as more code is needed.
For development time schema upgrades where data loss is not an issue, you can just use execSQL("DROP TABLE IF EXISTS <tablename>") in to remove your existing tables and call onCreate() to recreate the database.
For released versions, you should implement data migration in onUpgrade() so your users don't lose their data.
To further add missing points here, as per the request by Jaskey
Database version is stored within the SQLite database file.
catch is the constructor
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
So when the database helper constructor is called with a name (2nd param), platform checks if the database exists or not and if the database exists, it gets the version information from the database file header and triggers the right call back
As already explained in the older answer, if the database with the name doesn't exists, it triggers onCreate.
Below explanation explains onUpgrade case with an example.
Say, your first version of application had the DatabaseHelper (extending SQLiteOpenHelper) with constructor passing version as 1 and then you provided an upgraded application with the new source code having version passed as 2, then automatically when the DatabaseHelper is constructed, platform triggers onUpgrade by seeing the file already exists, but the version is lower than the current version which you have passed.
Now say you are planing to give a third version of application with db version as 3 (db version is increased only when database schema is to be modified). In such incremental upgrades, you have to write the upgrade logic from each version incrementally for a better maintainable code
Example pseudo code below:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
//upgrade logic from version 1 to 2
case 2:
//upgrade logic from version 2 to 3
case 3:
//upgrade logic from version 3 to 4
break;
default:
throw new IllegalStateException(
"onUpgrade() with unknown oldVersion " + oldVersion);
}
}
Notice the missing break statement in case 1 and 2. This is what I mean by incremental upgrade.
Say if the old version is 2 and new version is 4, then the logic will upgrade the database from 2 to 3 and then to 4
If old version is 3 and new version is 4, it will just run the upgrade logic for 3 to 4
onCreate()
When we create DataBase at a first time (i.e Database is not exists) onCreate() create database with version which is passed in
SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
onCreate() method is creating the tables you’ve defined and executing any other code you’ve written. However, this method will only be called if the SQLite file is missing in your app’s data directory (/data/data/your.apps.classpath/databases).
This method will not be called if you’ve changed your code and relaunched in the emulator. If you want onCreate() to run you need to use adb to delete the SQLite database file.
onUpgrade()
SQLiteOpenHelper should call the super constructor.
The onUpgrade() method will only be called when the version integer is larger than the current version running in the app.
If you want the onUpgrade() method to be called, you need to increment the version number in your code.
May be I am too late but I would like to share my short and sweet answer.
Please check Answer for a same problem. It will definitely help you. No more deep specifications.
If you are confident about syntax for creating table, than it may happen when you add new column in your same table, for that...
1) Uninstall from your device and run it again.
OR
2) Setting -> app -> ClearData
OR
3) Change DATABASE_VERSION in your "DatabaseHandler" class (If you have added new column than it will upgrade automatically)
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
OR
4) Change DATABASE_NAME in your "DatabaseHandler" class (I faced same problem. But I succeed by changing DATABASE_NAME.)
Points to remember when extending SQLiteOpenHelper
super(context, DBName, null, DBversion); - This should be invoked first line of constructor
override onCreate and onUpgrade (if needed)
onCreate will be invoked only when getWritableDatabase() or getReadableDatabase() is executed. And this will only invoked once when a DBName specified in the first step is not available. You can add create table query on onCreate method
Whenever you want to add new table just change DBversion and do the queries in onUpgrade table or simply uninstall then install the app.
You can create database & table like
public class DbHelper extends SQLiteOpenHelper {
private static final String DBNAME = "testdatbase.db";
private static final int VERSION = 1;
public DbHelper(Context context) {
super(context, DBNAME, null, VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table BookDb(id integer primary key autoincrement,BookName text,Author text,IssuedOn text,DueDate text,Fine text,Totalfine text");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS BookDb");
onCreate(db);
}
}
Note : if you want create another table or add columns or no such table, just increment the VERSION
onCreate is called for the first time when creation of tables are needed. We need to override this method where we write the script for table creation which is executed by SQLiteDatabase. execSQL method. After executing in first time deployment, this method will not be called onwards.
onUpgrade
This method is called when database version is upgraded. Suppose for the first time deployment , database version was 1 and in second deployment there was change in database structure like adding extra column in table. Suppose database version is 2 now.
Sqlite database override two methods
1) onCreate():
This method invoked only once when the application is start at first time . So it called only once
2)onUpgrade()
This method called when we change the database version,then this methods gets invoked.It is used for the alter the table structure like adding new column after creating DB Schema
Uninstall your application from the emulator or device. Run the app again. (OnCreate() is not executed when the database already exists)
no such table found is mainly when you have not opened the SQLiteOpenHelper class with getwritabledata() and before this you also have to call make constructor with databasename & version.
And OnUpgrade is called whenever there is upgrade value in version number given in SQLiteOpenHelper class.
Below is the code snippet (No such column found may be because of spell in column name):
public class database_db {
entry_data endb;
String file_name="Record.db";
SQLiteDatabase sq;
public database_db(Context c)
{
endb=new entry_data(c, file_name, null, 8);
}
public database_db open()
{
sq=endb.getWritableDatabase();
return this;
}
public Cursor getdata(String table)
{
return sq.query(table, null, null, null, null, null, null);
}
public long insert_data(String table,ContentValues value)
{
return sq.insert(table, null, value);
}
public void close()
{
sq.close();
}
public void delete(String table)
{
sq.delete(table,null,null);
}
}
class entry_data extends SQLiteOpenHelper
{
public entry_data(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase sqdb) {
// TODO Auto-generated method stub
sqdb.execSQL("CREATE TABLE IF NOT EXISTS 'YOUR_TABLE_NAME'(Column_1 text not null,Column_2 text not null);");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
}
If you forget to provide a "name" string as the second argument to the constructor, it creates an "in-memory" database which gets erased when you close the app.
Your database name must end with .db also your query strings must have a terminator (;)
Recheck your query in ur DatabaseHandler/DatabaseManager class(which ever you have took)
In my case I get items from XML-file with <string-array>, where I store <item>s. In these <item>s I hold SQL strings and apply one-by-one with databaseBuilder.addMigrations(migration). I made one mistake, forgot to add \ before quote and got the exception:
android.database.sqlite.SQLiteException: no such column: some_value (code 1 SQLITE_ERROR): , while compiling: INSERT INTO table_name(id, name) VALUES(1, some_value)
So, this is a right variant:
<item>
INSERT INTO table_name(id, name) VALUES(1, \"some_value\")
</item>
Sqliteopenhelper's method have methods create and upgrade,create is used when any table is first time created and upgrade method will called everytime whenever table's number of column is changed.
I have five tables in my sqlite db, the five tables are created in oncreate method if I make changes to one table in upgrade method based on the previous db version when I launched the app the changes are made I can see through my logcat but it calls oncreate method and say the 4 tables already exist. How can I handle this error?
public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
if (version_old < 3) {
database.execSQL(queryFive);
}
on onCreate I have statements that creates table initially which is then called again after onUpgrade and triggering the error they already exist. How can I handle this? Thanks.
If you make changes in one table, you should increment the DATABASE_VERSION = 1,2,3 and so on.
Whenever changes are done in database, you should first drop (delete) all table and create them again.
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); // drop table(s),if you have five tables , drop all five
onCreate(db); // this will create all tables again
}
Update : in case of not loosing old data of other tables
You need an abstract class that implements the upgrade process described here. Then you extend this abstract class for each of your tables. In your abstract class you must store you tables in a way(list, hardcoded) so when the onUpgrade fires you iterate over the table items and for each table item you do the described steps. They will be self upgraded, keeping all their existing details. Please note that the onUpgrade event fires only once per database, that's why you need to iterate over all your tables to do the upgrade of all of them. You maintain only 1 version number over all the database.
beginTransaction
run a table creation with if not exists (we are doing an upgrade, so the table might not exists yet, it will fail alter and drop)
put in a list the existing columns List<String> columns = DBUtils.GetColumns(db, TableName);
backup table (ALTER table " + TableName + " RENAME TO 'temp_" + TableName)
create new table (the newest table creation schema)
get the intersection with the new columns, this time columns taken from the upgraded table (columns.retainAll(DBUtils.GetColumns(db, TableName));)
restore data (String cols = StringUtils.join(columns, ",");
db.execSQL(String.format(
"INSERT INTO %s (%s) SELECT %s from temp_%s",
TableName, cols, cols, TableName));
)
remove backup table (DROP table 'temp_" + TableName)
setTransactionSuccessful
other than that, there is not way you can achieve this. unless, you can create separate db file for each table.
Probably there is somewhere here answer to my question, but if it exist I can't find it.
Here is my problem:
I have provided database in assets folder. When I want to update my app because I put some more rows in specific table I increase db version, call this.getWritableDatabase(); and onUpgrade is called, to this point everything is ok.
But what next?
Here is my onUpgrade function:
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
if(i < i2) {
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,SQLiteDatabase.OPEN_READWRITE);
db.execSQL("attach database ? as newdb", new String[]{DB_PATH + DB_NAME}); // I have to attach new version of db to the old one and then i can go on
db.execSQL("delete from GAME");
db.execSQL("INSERT INTO GAME SELECT * FROM newdb.GAME");
db.close();
}
This gives me an error that my db is locked - on the line:
db.execSQL("INSERT INTO GAME SELECT * FROM newdb.GAME");
I tried a lot of different scenarious but I just can't make it.
I'll be very glad if someone could help me make it works ;)
If your onUpgrade does not use its first parameter, it does something wrong.
db and newdb are the same database (both times opened with DB_PATH + DB_NAME).
You probably want to replace db with sqLiteDatabase.
onUpgrade means that you want to upgrade your database, not to copy some data from old one to new. this method gives you all you need to do upgrade - db instance to roll upgrade scripts for specific version. SQL is very powerful you can add/remove columns, delete tables and so on, so I don't see a reason to make another file.
I am trying to insert into two tables within one transaction, the insert works as when i do it it return the id of the new row for both tables but it look like it is not being committed to the tables
db.beginTransactionWithListenerNonExclusive(this);
try{
db.insertWithOnConflict(TABLE_NAME1, null, values, SQLiteDatabase.CONFLICT_ROLLBACK);
db.insertWithOnConflict(TABLE_NAME2, null, values, SQLiteDatabase.CONFLICT_ROLLBACK);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
db.close();
}
clarification, only when inserting to more than one table it doesn't work, when inserting to one table it work.
note: I checked if the insert operations were successful and they were, but committing the rows to the tables is what fails
end and begin transaction after each table, issue can be solved
I'm adding a table to my app's SQLite DB. All my syntax there is fine, not the issue. But I'm having some trouble getting the new table to be created properly. I added the new table....
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
db.execSQL(CREATE_REQUESTS);
db.execSQL(CREATE_OVERRIDE);
}
My on create method. I have 3 tables. When I updated the version number, I got an error saying "table requests (referring to CREATE_REQUESTS) has already been created." A look at my onUpgrade method...
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
Led me to understand that the line db.execSQL("DROP TABLE IF EXISTS contacts"), which refers to my DATABASE_CREATE table in the onCreate method, is used to drop the old table, then the next line, onCreate(db); recreates it. I did not add requests into that execSQL line, which is what caused the error. Here is the issue: I would rather not lose the data in the two tables I already have. Is there a way to add a table like I am trying to do, and not lose all the old data? Thanks.
You can do anything you want in onUpgrade. You can use ALTER to add new columns to your table.
Worst case, if your schema is completely and entirely different, you'll have to create the new table, populate it using data from the old table, and then delete the old table.
In any case, onUpgrade was designed to allow for a smooth upgrade without any loss of data. It's just up to you to implement it properly.
if DB version : 6
Ex : There is a table with 5 columns
When you upgrade to : 7 ( I am adding 1 new column in the 3 tables)
1. We need to add the columns when creating a table
2. onUpgrade method:
if (oldVersion < 7)
{
db.execSQL(DATABASE_ALTER_ADD_PAPER_PAID);
db.execSQL(DATABASE_ALTER_LAST_UPLOADED);
db.execSQL(DATABASE_ALTER_PAPER_LABEL);
}
Where : "DATABASE_ALTER_ADD_PAPER_PAID" is query.
EX: public static final String DATABASE_ALTER_ADD_PAPER_PAID = "ALTER TABLE "
+ TableConstants.MY_PAPERS_TABLE + " ADD COLUMN " + COLUMN_PAPER_PAID + " TEXT;";
After above two operation it will works fine for the fresh install user and app upgrade user