Social

Wednesday, January 1, 2014

SQLite Android JAVA Tutorial 02 – Connecting to DB & Create a table


Connecting to DB :
First you need to import android.database.sqlite.SQLiteDatabase,

import android.database.sqlite.SQLiteDatabase;

Now within the main class create a variable using SQLiteDatabase class. Using that variable we are going to do create OR open a database called “testDB”. If the “testDB” is previously created then it will open. And if the “testDB” not found the it will be created and open it.
The following JAVA program shows how to do that.

public class Sqlite_Tute extends Activity {
      
       SQLiteDatabase db;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              // TODO Auto-generated method stub
              super.onCreate(savedInstanceState);
              requestWindowFeature(Window.FEATURE_NO_TITLE);
              setContentView(R.layout.sqlite_tute);
             
             
              try
              {
                     db = openOrCreateDatabase("testDB", MODE_PRIVATE,null);                            }
              catch(Exception e)
              {
                     Log.d("rockman", "DB Creation ERROR--"+e.toString());
              }
       }
}


Create a table :
Same as connecting to DB, using SQLiteDatabase variable (db) can create a table in that DB (“testDB”). It only create the table only if the table is not exist.
Let’s create the following table,

public class Sqlite_Tute extends Activity {
      
       SQLiteDatabase db;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              // TODO Auto-generated method stub
              super.onCreate(savedInstanceState);
              requestWindowFeature(Window.FEATURE_NO_TITLE);
              setContentView(R.layout.sqlite_tute);
             
             
              try
              {
                     db.execSQL("CREATE TABLE IF NOT EXISTS test_table (_id INTEGER PRIMARY KEY AUTOINCREMENT,_name TEXT,_email TEXT,_age INTEGER);");
              }
              catch(Exception e)
              {
                     Log.d("rockman", "TABLE Creation ERROR--"+e.toString());
              }
       }
}

And the data types that you can use are,
  •  NULL. The value is a NULL value.
  •  INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
  •  REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
  •  TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).
  •  BLOB. The value is a blob of data, stored exactly as it was input.



No comments:

Post a Comment

 

Search This Blog

Most Reading

Protected by Copyscape Duplicate Content Software

Facebook Page