Search This Blog

Friday 14 September 2012

Adding data to an SQL database


In the last post we looked at setting up the schema for an SQL database and creating the database.  Today we will look at how data would be added to the database.

As usual we will be using my Maths Test App as the basis of examples, so if you have not downloaded it, do this now (This can be done by searching Google Play for 'Sundev Pabla').

Data is added to the SQL database by creating an instance of the ContentValues class and populating the class with the data you want to put in the database (the ContentValues class provides the 'put' method for this purpose).  Finally the insert method on the database is called and the name of the Database table and the instance of the ContentValues class are passed in as arguments of the insert function.

Below is the code I use to add a top score to the SQL database in my maths test app.  This addTopScore function is a method of the MathsTestDbAdapter Class we discussed in the previous post.  You should be able to see that I create an instance of the ContentValues class which is provided by the Android API (So you will need the following import statement at the top of file in which this method is implemented):

import android.content.ContentValues;

I then 'put' the data I want to store in the database into the object I instantiated from the ContentValues class.  Finally I call the insert method on the database object and pass in the name of the table where I want the data stored along with the data I want stored.  The insert function returns a long which is a unique identifier for the row just stored.

 public long addTopScore(String initials,Double score)
    {
    // This function adds a high score to the database
    // The initials and score of the high scorer are passed in, info
    // about the game level and type are obtained from the preset user
    // preferences
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_USER_INITIALS, initials);
    initialValues.put(KEY_SCORE, score);
    initialValues.put(KEY_LEVEL, cUserPreferences.gameLevel);
    initialValues.put(KEY_GAME_TYPE, cUserPreferences.gameType);
   
    return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

I  think that is enough for today, as usual if you have any questions please get in touch via the blog.

No comments:

Post a Comment