cybergraph

Helper

Dec 29th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. 1 import android.content.ContentValues;
  2. 2 import android.content.Context;
  3. 3 import android.database.Cursor;
  4. 4 import android.database.sqlite.SQLiteDatabase;
  5. 5 import android.database.sqlite.SQLiteOpenHelper;
  6. 6
  7. 7
  8. 8 public class DatabaseHelper extends SQLiteOpenHelper {
  9. 9
  10. 10 public final static String DATABASE_NAME = "Student.db";
  11. 11 public final static String TABLE_NAME = "student_table";
  12. 12 public static final String COL_1 = "ID";
  13. 13 public static final String COL_2 = "NAME";
  14. 14 public static final String COL_3 = "SURNAME";
  15. 15 public static final String COL_4 = "MARKS";
  16. 16
  17. 17 public DatabaseHelper(Context context) {
  18. 18 super(context, DATABASE_NAME, null, 1);
  19. 19 }
  20. 20
  21. 21 @Override
  22. 22 public void onCreate(SQLiteDatabase db) {
  23. 23 db.execSQL("CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARKS INTEGER)");
  24. 24 }
  25. 25
  26. 26 @Override
  27. 27 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  28. 28 db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
  29. 29 onCreate(db);
  30. 30 }
  31. 31
  32. 32 public boolean insertData(String name, String surname, String marks) {
  33. 33 SQLiteDatabase db = this.getWritableDatabase();
  34. 34 ContentValues cv = new ContentValues();
  35. 35 cv.put(COL_2, name);
  36. 36 cv.put(COL_3, surname);
  37. 37 cv.put(COL_4, marks);
  38. 38 long result = db.insert(TABLE_NAME, null, cv);
  39. 39 if (result == -1) return false;
  40. 40 else return true;
  41. 41 }
  42. 42
  43. 43 public Cursor getData(String id){
  44. 44 SQLiteDatabase db = this.getWritableDatabase();
  45. 45 String query="SELECT * FROM "+TABLE_NAME+" WHERE ID='"+id+"'";
  46. 46 Cursor cursor = db.rawQuery(query,null);
  47. 47 return cursor;
  48. 48 }
  49. 49
  50. 50 public boolean updateData(String id, String name, String surname, String marks) {
  51. 51 SQLiteDatabase db = this.getWritableDatabase();
  52. 52 ContentValues contentValues = new ContentValues();
  53. 53 contentValues.put(COL_1, id);
  54. 54 contentValues.put(COL_2, name);
  55. 55 contentValues.put(COL_3, surname);
  56. 56 contentValues.put(COL_4, marks);
  57. 57 db.update(TABLE_NAME, contentValues, "ID=?", new String[]{id});
  58. 58 return true;
  59. 59 }
  60. 60
  61. 61 public Integer deleteData (String id) {
  62. 62 SQLiteDatabase db = this.getWritableDatabase();
  63. 63 return db.delete(TABLE_NAME, "ID = ?", new String[]{id});
  64. 64 }
  65. 65
  66. 66 public Cursor getAllData() {
  67. 67 SQLiteDatabase db = this.getWritableDatabase();
  68. 68 Cursor res = db.rawQuery("SELECT * FROM "+TABLE_NAME, null);
  69. 69 return res;
  70. 70 }
  71. 71 }
Add Comment
Please, Sign In to add comment