在 Android 应用中使用 SQLite 数据库并使用 SQL 查询语句实现关键字搜索功能。
示例代码如下:
public class MyDatabaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "my_database"; private static final int DB_VERSION = 1; private static final String CREATE_TABLE_SQL = "create table my_table (" + "_id integer primary key autoincrement," + "name text," + "age integer);";
public MyDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < newVersion) {
db.execSQL("drop table if exists my_table");
onCreate(db);
}
}
}
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this); SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from my_table where name like ?", new String[] {"%关键字%"});
while (cursor.moveToNext()) { int id = cursor.getInt(0); String name = cursor.getString(1); int age = cursor.getInt(2); // Do something with the data }
cursor.close(); db.close();
下一篇:本地数据库转在线数据库