Insert into DB :
Let’s say we need to insert a raw of data now. The following Java program shows how we can insert records in our test_table created in previous post.
public class Sqlite_Tute extends Activity {SQLiteDatabase db;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.sqlite_tute);try{db = openOrCreateDatabase("testDB", MODE_PRIVATE,null);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", "DB Creation or TABLE Creation ERROR--"+e.toString());}/////////////////////////// INSERT PARTString name = ”Rockman”;String email = ”test@test.com”;int age = 24;try{ContentValues values = new ContentValues();values.put("_name", name);values.put("_email", email);values.put("_age", age);db.insert("test_table", null, values);}catch(Exception e){Log.d("rockman", "INSERT ERROR--"+e.toString());}}}
NOTE – “_id” attribute will be an auto incremental value so no need to insert it. And here you can insert any type of data by using the “put” command. Just make sure you put correct type of data to correct table column.
Select from DB :
Following Java program shows how we can fetch and display records from our test_table created.
public class Sqlite_Tute extends Activity {SQLiteDatabase db;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.sqlite_tute);try{db = openOrCreateDatabase("testDB", MODE_PRIVATE,null);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", "DB Creation or TABLE Creation ERROR--"+e.toString());}/////////////////////////// SELECT PARTtry{Cursor cursor =db.rawQuery("SELECT * FROM test_table", null);while(cursor.moveToNext()){Log.d("rockman", "----- NEW VALUE SET -----");int id = cursor.getInt(0);Log.d("rockman", "id - "+id);String name = cursor.getString(1);Log.d("rockman", "name - "+name);String email = cursor.getString(2);Log.d("rockman", "email - "+email);int age = cursor.getInt(3);Log.d("rockman", "age - "+age);}cursor.close();}catch(Exception e){Log.d("rockman", "SELECT ERROR--"+e.toString());}}}
NOTE – Using Cursor class you can load the values that was generated by the query. These queries are normal mysql commands. In here you need to change the command based on the type of the data.
For integers -> getInt(x)
For Strings -> getString(x)
For Blob -> getBlob(x)
**here x represent the column number which begins from 0.
No comments:
Post a Comment