android应用开发中常常需要记录一下数据,而在查询的时候如何实现模糊查询呢?很少有文章来做这样的介绍,所以这里简单的介绍下三种sqlite的模糊查询方式,直接上代码把:
package com.example.utils; import java.util.ArrayList; import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log; public class DBManage extends SQLiteOpenHelper { static int init_version = 1;
static String database_name = "android_sqlite_test.db";
static String tab_name = "uer_log";
static String tab_field01 = "_id";
static String tab_field02 = "log_name";
SQLiteDatabase mDatabase; public DBManage(Context context) {
super(context, database_name, null, init_version);
// TODO Auto-generated constructor stub
mDatabase = getWritableDatabase();
} @Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "create table " + tab_name + " ( " + tab_field01
+ " integer primary key , " + tab_field02 + " text not null) "; db.execSQL(sql);
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub } /**
* 插入记录
*
* @param u
* @return
*/
public boolean insertData(String... str) { int request_int = 0;
for (int i = 0; i < str.length; i++) { // 实例化一个ContentValues 对象 ,作用,收集数据,方便于SQLite执行增,删,改,查
ContentValues contentValues = new ContentValues();
contentValues.put(tab_field02, str[i]);
mDatabase.insert(tab_name, null, contentValues);
request_int++;
}
return str.length == request_int;
} // 根据条件模糊查询数据库数据
public ArrayList<String> query(int top_int, String... str) {
ArrayList<String> result_list = new ArrayList<String>();
mDatabase = getReadableDatabase();
//模糊查询的三种方式:
/*
* 全部查询
String current_sql_sel = "SELECT * FROM " + tab_name;
Cursor c = mDatabase.rawQuery(current_sql_sel, null);*/ //1.使用这种query方法%号前不能加' ;
Cursor c_test = mDatabase.query(tab_name, new String[]{tab_field02}, tab_field02+" LIKE ? ",
new String[] { "%" + str[0] + "%" }, null, null, null); //2.使用这种query方法%号前必须加' ;
// Cursor c_test=mDatabase.query(tab_name, new String[]{tab_field02},tab_field02+" like '%" + str[0] + "%'", null, null, null, null); //3.使用这种方式必须在%号前加' ;
String current_sql_sel = "SELECT * FROM "+tab_name +" where "+tab_field02+" like '%"+str[0]+"%'";
//Cursor c_test = mDatabase.rawQuery(current_sql_sel, null); Log.e("tag", "查询完成...");
while (c_test.moveToNext()) {
String name = c_test.getString(c_test.getColumnIndex(tab_field02));
//name.contains(str[0]);
// 让集合中的数据不重复;
if (!result_list.contains(name)) {
result_list.add(name);
Log.e("tag", name);
}
}
c_test.close(); return result_list;
} }
转载请注明出处:
http://blog.csdn.net/fth826595345/article/details/9199235