运行原始sqlite查询

时间:2014-10-27 12:18:39

标签: android sqlite

我正在尝试运行此查询,但它无法正常工作,我似乎无法找到它的错误。

public boolean verifyUser(String name , String pword){
   boolean result = false;
   SQLiteDatabase db = this.getReadableDatabase();
   try {   
   Cursor res =  db.rawQuery( "select * from user where username="+name+" and password="+pword+"", null );

      int count = res.getCount(); 

      res.moveToFirst();
      if (count == 0) 
      {
          result = false;
      }
      else{
        result = true;
      }
   }
      catch (SQLiteException se ) {
          Log.e(getClass().getSimpleName(), "Could not log in");
      }
      return result;
      //return true;
   }

3 个答案:

答案 0 :(得分:3)

在SQL中,您需要将字符串文字放在'single quotes'中。更好的是,使用参数:

Cursor res =  db.rawQuery( "select * from user where username=? and password=?",
    new String[] { name, pword } );

答案 1 :(得分:0)

复制并粘贴以下查询

select * from user where username='"+name+"' and password='"+pword+"'"

实际上你错过了单引号

答案 2 :(得分:0)

选中此项,编辑了您的代码。

public boolean verifyUser(String name , String pword){
   boolean result = false;
   SQLiteDatabase db = this.getReadableDatabase();
   try {   
   Cursor res =  db.rawQuery( "select * from user where username='"+name+"' and password='"+pword+"'", null );

      int count = res.getCount(); 

      //res.moveToFirst(); //Remove this line (It may be crashing because of this line.)
      if (count == 0) 
      {
          result = false;
      }
      else{
       res.moveToFirst();
        result = true;
      }
   }
      catch (SQLiteException se ) {
          Log.e(getClass().getSimpleName(), "Could not log in");
      }
      return result;
      //return true;
   }