android query 模糊查询怎么使用_百度知道

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);

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;
}

}

来源URL:http://zhidao.baidu.com/link?url=KbYHCEIhKUJWqHJIhoWblM6nEau-6jjsKnn-LAq6rm0M-HKZ7nL4jFpvGQGife6UJkcPMbRa–TQqfTokMjKDiiP0Op7XP1aVdzfEzZsK6q