在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数据库。开发者可以根据实际需求进行更复杂的数据库操作,如查询、更新、删除等操作。