Android DB Connectivity
Android DB Connectivity
Step:1
Create java class for all DB Operations at the location where mainactivity.java file is present i.e.
appjavacom.example…. --> right click new class
give the name as “DBHelper”
======== Code in DBHelper.java============
step:2
Extend this class using SQLiteOpenHelper
hover and click on implement methods
hover and define constructor and keep only context part and remove the remaining par.
Step:3
declare following objects globally
1. private static final String DB_NAME="STUDDB.db";
2. private static final int DB_VERSION=1;
3. private static final String TB_NAME="studinfo";
4. private static final String COL1="sid";
5. private static final String COL2="sname";
6. ContentValues valOb = new ContentValues();
7. Context conObj;
Step:4
Create method to insert record as:
public long insertRec(int sid,String sname)
{
1. long rst=-1;
2. SQLiteDatabase sqldb=this.getWritableDatabase();
3. try {
4. valOb.put(COL1,sid);
5. valOb.put(COL2, sname);
6. rst=sqldb.insertOrThrow(TB_NAME,null,valOb);
7. }catch(SQLiteConstraintException ex1) {
8. Toast.makeText(conObj, ex1.getMessage(), Toast.LENGTH_SHORT).show();
9. }
10. catch(SQLiteDatabaseLockedException ex2)
11. { Toast.makeText(conObj, ex2.getMessage(), Toast.LENGTH_SHORT).show();}
12. catch(Exception ex3){Toast.makeText(conObj, ex3.getMessage(), Toast.LENGTH_SHORT).show();}
13. finally {
14. sqldb.close();
15. }
16. return rst;
}
Step:5
Create method to Read record as:
1. public Cursor getData()
2. {
3. SQLiteDatabase sqldb=this.getReadableDatabase();
4. return sqldb.query(TB_NAME,null,null,null,null,null,null);
5. }