sql查询不传递参数

时间:2015-06-27 12:53:26

标签: android sqlite

我正在编写一个Android应用程序,我需要搜索数据库,这是我使用的方法:

public Cursor getData(String table, String keyword, SQLiteDatabase db){

    String selection;
    Cursor cursor;

    switch (table){
        case "User":
            String [] projection = {id,name,phone};
            selection = "username LIKE ?";
            String [] selection_arg = {keyword};
            cursor = db.query("User",projection,selection,selection_arg,null,null,null);
            break;
        //omitted
        default:
            return null;
    }
    return cursor;

用户输入关键字

keyword = search_user.getText().toString();
Cursor cursor = dbHelper.getData(ShippingApplication.User.USER_TABLE,keyword,db);

代码不起作用,当我调试时,我看到db变量的mQuery是: SQLiteQuery: SELECT userID, userName, phoneNumber FROM User WHERE userName LIKE ? 看起来查询没有将关键字的值传递给sql命令。 有人能告诉我什么是错的吗?

编辑2:我稍微更改了代码,现在它可以正常工作:

String selection = ShippingApplication.User.name + " LIKE '%" + keyword + "%'";
Cursor cursor = db.query(The table name,projection,selection,null,null,null,null);

1 个答案:

答案 0 :(得分:0)

试试这种方式

请检查您的SQLiteDatabase对象是否为空

之后检查表是否已创建

我得到光标计数我已经调试了它并且它对我来说工作正常

public Cursor getData(String table, String keyword, SQLiteDatabase db){

        String selection;
        Cursor cursor;

        switch (table){
            case "Tbl_staticContent":
                String [] projection = {"PageTitle","Content"};
                selection = "PageTitle LIKE ?";
                String [] selection_arg = {keyword};
                cursor = db.query("Tbl_staticContent",projection,selection,selection_arg,null,null,null);

                Log.e("count",""+cursor.getCount());
                //I have create table and stored data and also check the like condtion also it's work fine and get the cursor.getCount() > 0 also .

                break;

            default:
                return null;
        }
        return cursor;
}