我正在创建一个Android应用程序,我将需要使用SQLite存储数据。它需要存储日期,两个日期之间的天数和一些文本字段。我已经在线查找了一些教程,我最熟悉的方法就是这个:
public class DataHelper {
private static final String DATABASE_NAME = "example.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "table1";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public List<String> selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
抱歉代码很长。我不确定这种使用数据库的方式是否正确
答案 0 :(得分:2)
DataHelper
走在正确的轨道上。拥有DataHelper
来创建数据库和表是一个很好的计划。但是,让DataHelper
扩展SQLiteOpenHelper类,使其真正成为Helper
类。DataHelper
为这些表/类调用onCreate
方法。ContentProvider
,可帮助您提供对数据的访问。尝试严格通过您自己的ContentProvider
提供对数据库的访问权限。这提供了更好的灵活性和一些抽象级别。以下是我最近一直在使用的一些示例。这些来自其他来源,但稍作修改。我不知道我在哪里得到原始的东西。但这就是我所做的工作。
希望这有帮助!
//SimpleNotesDBHelper (Your `DataHelper`)
public class SimpleNotesDBHelper extends SQLiteOpenHelper {
private static final String NOTES_DATABASE_NAME = "simplenotes.db";
private static final int DB_VERSION = 1;
public SimpleNotesDBHelper(Context context) {
super(context, NOTES_DATABASE_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
NotesTable.onCreate(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
NotesTable.onUpgrade(db, oldVersion, newVersion);
}
}
//NotesTable (a seperate table in my db)
public class NotesTable {
public static final String NOTES_TABLE = "notes";
public static final String COL_ID = "_id";
public static final String COL_CATEGORY = "category";
public static final String COL_SUMMARY = "summary";
public static final String COL_DESCRIPTION = "description";
public static final String NOTES_TABLE_CREATE = "create table "
+ NOTES_TABLE
+ "("
+ COL_ID
+ " integer primary key autoincrement, "
+ COL_CATEGORY
+ " text not null, "
+ COL_SUMMARY
+ " text not null, "
+ COL_DESCRIPTION
+ " text not null"
+ ");";
public static void onCreate(SQLiteDatabase database) {
database.execSQL(NOTES_TABLE_CREATE);
insertingSomeTestData(database);
}
public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
database.execSQL("drop table if exists " + NOTES_TABLE);
onCreate(database);
}
}
//SimpleNotesContentProvider (a ContentProvider to my db)
public class SimpleNotesContentProvider extends ContentProvider {
private SimpleNotesDBHelper databaseHelper;
private static final int SIMPLE_NOTES = 10; //arbitrary
private static final int SIMPLE_NOTE_ID = 20; //arbitrary
private static final String AUTHORITY = "ashton.learning.projects.simplenotes.contentprovider";
private static final String BASE_PATH = "simplenotes";
private static final String DIR_BASE_TYPE = "simplenotes";
private static final String ITEM_BASE_TYPE = "simplenote";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + DIR_BASE_TYPE;
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + ITEM_BASE_TYPE;
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
int rowsDeleted = 0;
switch (uriType) {
case SIMPLE_NOTES:
rowsDeleted = db.delete(NotesTable.NOTES_TABLE, selection, selectionArgs);
break;
case SIMPLE_NOTE_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = db.delete(NotesTable.NOTES_TABLE,
NotesTable.COL_ID + "=" + id,
null);
}
else {
rowsDeleted = db.delete(NotesTable.NOTES_TABLE,
NotesTable.COL_ID + "=" + id + " and " + selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
int rowsDeleted = 0;
long id = 0;
switch(uriType) {
case SIMPLE_NOTES:
id = db.insert(NotesTable.NOTES_TABLE, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH + "/" + id);
}
@Override
public boolean onCreate() {
databaseHelper = new SimpleNotesDBHelper(getContext());
sURIMatcher.addURI(AUTHORITY, BASE_PATH, SIMPLE_NOTES);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", SIMPLE_NOTE_ID);
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(NotesTable.NOTES_TABLE);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case SIMPLE_NOTES:
break;
case SIMPLE_NOTE_ID:
queryBuilder.appendWhere(NotesTable.COL_ID
+ "="
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = databaseHelper.getWritableDatabase();
Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case SIMPLE_NOTES:
rowsUpdated = db.update(NotesTable.NOTES_TABLE,
values,
selection,
selectionArgs);
break;
case SIMPLE_NOTE_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = db.update(NotesTable.NOTES_TABLE,
values,
NotesTable.COL_ID + "=" + id,
null);
}
else {
rowsUpdated = db.update(NotesTable.NOTES_TABLE,
values,
NotesTable.COL_ID + "=" + id + " and " + selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
}