About the update of SQLite in Android.When you change the structure of the datebase,how can we update the datebase without delete the data?
You should override the onUpgrade Method in the SQLiteOpenHelper. You should code something like this.
public void onUpgrade (SQLiteDatabase db,int oldVersion,int newVersion){
String update = ALTER TABLE <table_name> ADD COLUMN <column_name> <column_type>;
db.execSQL(update);
}
Dropping a table, adding a row, inserting/updating/deleting data should be done here.
Alter Table gives you very limited options in performing an update to the database tables. If you want to copy your data into a completely new structure, you should think about creating temporary tables where you can copy data, create the new schema and then copy your data from the temporary tables to the new table, in this upgrade method.
Make sure you have your DB Version numbers correctly updated while creating the DBHelper.
Related
I am working on a project on android where thousands of tables exist.Unfortunately I do not have fresh data base so what can I do to delete all record from all tables. i am using sqlite database .If it is possible please tell me.
If you want to remove the entire rows/data from table, then it's better to drop the table and recreate it. This is the usual convention and for this reason SqLiteOpenHelper has onCreate() and onUpgrade() method which creates table or upgrades it, when table is dropped, or database version is changed
For deleting/dropping table, the code fragment is
db.execSQL("DROP TABLE IF EXISTS " + YOUR_TABLE);
Check the first answer for reference What happens if an android app, which creates database, is then uninstalled?
I have done a few searches and read a number of posts but I am still not successful trying to update a database without losing the data that is already saved.
I created the DB using this tutorial: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
In the new database I want to migrate data from a main table to a new table that will store the user's favourites. Currently, they are stored in the main table. In the onupgrade function I tried renaming the table and inserting the record into the new table. That didn't work. I also tried saving the data to a cursor and then populating the new table but that didn't work. For these methods, I got errors saying that the new/old table cannot be found.
Below is the onUpgrade() function.
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE books rename to old_books");
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
db.execSQL("INSERT into favourites (_id, type, title, notes,rating) SELECT _id ,type, title, notes, rating FROM old_books where rating > 0;");
db.execSQL("DROP TABLE IF EXISTS old_books;");
}
}
Is there a better way to update the database without losing data using the implementation from the tutorial? All I need to do is copy the favourites from the "books" table and load them to the "favourites" table when users update the app.
onUpgrade is called while the database is open and a transaction is active.
You cannot overwrite the database file at this time (and this would lose all the data in the old file).
Just remove the copyDataBase() call.
if you are using SQLite browser to get preloaded database so you can update the database file then change it's version not create a new database file and keep the data ! Source tutorial .... in my opinion this tutorial is better and more detailed than the one you refereed.
I have an app released in app store
I want to add a new column to the user table in the sqlite db and want it to be not null
But I also want old users to be able to use the app
What will happen if an old user updates their app with the new version? At login, I get the info from the server and I insert it in the db. The db insertion will probably stop when there is no value for the new column
Also, how do I do the upgrade itself?
in onUpgrade I do "ALTER table USER..."
in the constructor of the SQLite helper I add the new DB version
what else?
Also, I've added 3-4 totally new tables needed for new features. I've called their create queries in the onCreate method of the SQLite helper. Should I do anything else in addition to this?
in the constructor of the SQLite helper I add the new DB version
That will trigger onUpgrade(), good.
However, you cannot use ALTER TABLE to add a column with NOT NULL.
Here's what you can do in onUpgrade() to preserve user data:
Rename the old table to a temporary name
Recreate the table with the new column and NOT NULL
Populate the new table from the old temp table and supply the new column a reasonable non-null default value
Drop the temporary table
Can you give me an example lets say table is called USER with fields NAME and EMAIL and now I want to add a new field AGE?
Here's an example:
sqlite> create table user(name, email);
sqlite> insert into user select 'foo','bar';
sqlite> alter table user rename to user_temp;
sqlite> create table user(name, email, age not null);
sqlite> insert into user select name,email,-1 from user_temp;
sqlite> drop table user_temp;
sqlite> select * from user;
name|email|age
foo|bar|-1
Also, I've added 3-4 totally new tables needed for new features. I've called their create queries in the onCreate method of the SQLite helper. Should I do anything else in addition to this?
should I put the new creates for the new tables in both onCreate and onUpgrade or only in onUpgrade?
Make sure the same new tables are created in onUpgrade().
onCreate() is only run when the database is created for the first time, not on upgrade.
After both onCreate() and onUpgrade() the database schema (table structure) should be compatible. How you implement it is up to you. Putting the CREATE TABLEs there in onUpgrade() is an option. Some people prefer to call onCreate() insinde onUpgrade(), which can cause some headache when trying to migrate old data.
When there is new data available to my Android application I need to completely remove all current entries in one of the SQLite database tables and replace them all with the new data. What is the best way to do this?
Would it be best to run
DELETE * FROM my_table
or
run a delete query for every row in the database
or run
database.execSQL(DATABASE_DROP_MY_TABLE);
database.execSQL(DATABASE_CREATE_MY_TABLE);
Where DATABASE_DROP_MY_TABLE is SQL to drop the table and DATABASE_CREATE_MY_TABLE is
SQL to create the table again with no entries.
And then following one of these, insert the new data.
Of course there are probably other ways to do this that I have not thought of.
Assuming you're using SQLiteOpenHelper, you can just close db, delete the whole file and recreate the db:
class MyDatabase extends SQLiteOpenHelper {
public static final String DB_NAME = "wat";
public MyDatabase(Context context) {
super(context, DB_NAME, null, CURRENT_VERSION);
}
}
dbHelper.close(); // dbHelper is your MyDatabase instance
context.deleteDatabase(DB_NAME);
SQLiteDatabase db = dbHelper.getWritableDatabase() // will create empty db
Nice thing about this solution is that you won't have to update table resetting code when you add new tables to your schema. It also correctly recreates indexes you might have added.
I wouldn't complicate things, and simply drop the table with DROP TABLE statement. As the doc say:
The SQLite DROP TABLE statement is used to remove a table definition and all associated data, indexes, triggers, constraints and permission specifications for that table.
You would have clean plate, then create the table again and add your new data.
I have a pre-established SQLite Database in my application. It has a table with rows about 20 rows of text. I want to be able to add additional rows to the table without deleting all of the previous information. The only way I have seen which would allow me to do this is to delete all of the previous databases and then recreate it with the new rows. There must be a better way. Thanks for your help!
Are you confusing rows with columns?
If you really do mean rows then as antlersoft points out, using the SQL INSERT INTO statement will simply add a new row to a table without affecting any existing table data. This is one of the most basic and commonly used SQL statements.
If you actually mean you need to add columns then use the SQL ALTER TABLE statement.
See..
SQL INSERT INTO statement
SQL ALTER TABLE statement
The Android framework, as it relates to SQLite (using a SQLiteOpenHelper) provides two distinct methods for handling database lifecycles - onCreate(), used when the database needs to be created from scratch, and onUpgrade(<database>, int oldVersion, int newVersion) for handling updates. You can specify the "new" version number in the constructor for the superclass of your SQLiteOpenHelper, and the framework knows to call onUpgrade() based on this parameter and the internal version # in the actual sqlite database.
So, to modify your database during a version change just override onUpgrade() and run whatever SQLite stuff that you need.