Android SQLiteHelper
View Code
1 package com.liren.news.data;
2
3 import android.content.ContentValues;
4 import android.content.Context;
5 import android.database.Cursor;
6 import android.database.sqlite.SQLiteDatabase;
7
8 public class SQLiteHelper extends android.database.sqlite.SQLiteOpenHelper {
9
10 private final static String DATABASE_NAME = "db_name";
11 private final static int DATABASE_VERSION = 1;
12 private final static String TABLE_NAME = "mytable";
13 private final static String FIELD_ID = "ID";
14 private final static String FIELD_NAME = "NAME";
15
16 public SQLiteHelper(Context context) {
17 super(context, DATABASE_NAME, null, DATABASE_VERSION);
18 }
19
20 @Override
21 public void onCreate(SQLiteDatabase db) {
22 String sql = "Create table %s (%s integer primary key autoincrement,%s text);";
23 sql = String.format(sql, TABLE_NAME, FIELD_ID, FIELD_NAME);
24 db.execSQL(sql);
25 }
26
27 @Override
28 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
29 String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
30 db.execSQL(sql);
31 onCreate(db);
32 }
33
34 public Cursor select() {
35 SQLiteDatabase db = this.getReadableDatabase();
36 Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null,
37 FIELD_ID);
38 return cursor;
39
40 }
41
42 public long insert(String name) {
43 SQLiteDatabase db = this.getWritableDatabase();
44 ContentValues cv = new ContentValues();
45 cv.put(FIELD_NAME, name);
46 long row = db.insert(TABLE_NAME, null, cv);
47 return row;
48 }
49
50 public void delete(int id){
51 SQLiteDatabase db = this.getWritableDatabase();
52 String where = FIELD_ID + "= ?";
53 String[] wherevalue = {Integer.toString(id)};
54 db.delete(TABLE_NAME, where, wherevalue);
55 }
56
57 public void update(int id,String name)
58 {
59 SQLiteDatabase db = this.getWritableDatabase();
60 String where = FIELD_ID + "= ?";
61 String[] wherevalue = {Integer.toString(id)};
62 ContentValues cv = new ContentValues();
63 cv.put(FIELD_NAME, name);
64 db.update(TABLE_NAME, cv, where, wherevalue);
65 }
66 }
67