超酷小 发表于 2016-11-29 10:15:51

SQLite操作类

public class ToDoDB extends SQLiteOpenHelper {

private final static String DATABASE_NAME = "todo_db";
private final static int DATABASE_VERSION = 1;
private final static String TABLE_NAME = "todo_table";
public final static String FIELD_id = "_id";
public final static String FIELD_TEXT = "todo_text";

public ToDoDB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public void onCreate(SQLiteDatabase db) {

String sql = "CREATE TABLE " + TABLE_NAME + " (" + FIELD_id
+ " INTEGER primary key autoincrement, " + " " + FIELD_TEXT
+ " text)";
db.execSQL(sql);
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}

public Cursor select() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db
.query(TABLE_NAME, null, null, null, null, null, null);
return cursor;
}

public long insert(String text) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(FIELD_TEXT, text);
long row = db.insert(TABLE_NAME, null, cv);
return row;
}

public void delete(int id) {
SQLiteDatabase db = this.getWritableDatabase();
String where = FIELD_id + " = ?";
String[] whereValue = { Integer.toString(id) };
db.delete(TABLE_NAME, where, whereValue);
}

public void update(int id, String text) {
SQLiteDatabase db = this.getWritableDatabase();
String where = FIELD_id + " = ?";
String[] whereValue = { Integer.toString(id) };
ContentValues cv = new ContentValues();
cv.put(FIELD_TEXT, text);
db.update(TABLE_NAME, cv, where, whereValue);
}

public Cursor test()
{
SQLiteDatabase db = this.getWritableDatabase();
//Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
//return cursor;
//db.execSQL("insert into todo_table(todo_text)values(\"QQ\")");
   String name = "";
   
   Cursor cur = db.rawQuery("select * from todo_table", null);
   /*
   cur.moveToFirst();
   while (!cur.isLast())
   {
   name = name+ cur.getInt(0)+"*"+cur.getString(1)+ "\r\n";
   cur.moveToNext();
   }name = name+ cur.getInt(0)+"*"+cur.getString(1)+ "\r\n";
   return name; */
   return cur;
}
}
页: [1]
查看完整版本: SQLite操作类