在Android中,可以使用SQLite数据库进行数据存储和检索。以下是使用Android数据库的一般步骤:
SQLiteOpenHelper
子类中创建数据库。在onCreate()
方法中,可以定义表和字段。public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase";
private static final int DATABASE_VERSION = 1;
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// 创建表和字段
String createTableQuery = "CREATE TABLE myTable (id INTEGER PRIMARY KEY, name TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升级数据库时执行的操作
}
}
getWritableDatabase()
或getReadableDatabase()
方法打开数据库。MyDatabaseHelper dbHelper = new MyDatabaseHelper(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
insert()
方法向表中插入数据。ContentValues values = new ContentValues();
values.put("id", 1);
values.put("name", "John");
long newRowId = db.insert("myTable", null, values);
query()
方法从表中检索数据。String[] projection = {"id", "name"};
String selection = "name = ?";
String[] selectionArgs = {"John"};
Cursor cursor = db.query("myTable", projection, selection, selectionArgs, null, null, null);
if (cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
// 处理数据
} while (cursor.moveToNext());
}
cursor.close();
update()
方法更新表中的数据。ContentValues values = new ContentValues();
values.put("name", "Jane");
String whereClause = "id = ?";
String[] whereArgs = {"1"};
int rowsUpdated = db.update("myTable", values, whereClause, whereArgs);
delete()
方法从表中删除数据。String whereClause = "id = ?";
String[] whereArgs = {"1"};
int rowsDeleted = db.delete("myTable", whereClause, whereArgs);
close()
方法关闭数据库。db.close();
以上是使用Android数据库的基本步骤,可以根据具体需求进行调整和扩展。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>