在Android開發中,可以使用SQLite數據庫來存儲和管理數據。以下是一個簡單的示例,介紹如何在Android應用中對接SQLite數據庫:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY, name TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String dropTableQuery = "DROP TABLE IF EXISTS mytable";
db.execSQL(dropTableQuery);
onCreate(db);
}
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
DatabaseHelper dbHelper = new DatabaseHelper(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", "John");
db.insert("mytable", null, values);
Cursor cursor = db.rawQuery("SELECT * FROM mytable", null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
Log.d("Database", "Name: " + name);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
以上是一個簡單的示例,介紹了如何在Android應用中對接SQLite數據庫。開發者可以根據實際需求進行更復雜的數據庫操作,如查詢、更新、刪除等操作。