开发者

how to compare the text field values with database values which is entered in the text field

Actually, I don't want to accept the same name which is already 开发者_StackOverflowentered in the text field (i.e; unique values) stored in database.

For example, I entered a name "health" in text field and saved it. If again enter the same name then it won't accept.

I tried below but it's not working. Please help me.

boolean ifExisting(String cat)
     {
      Cursor c = db.rawQuery("SELECT * FROM " + "restaurants" + "WHERE" + "category" + "=" + cat, null); 
         if(c.getCount() == 0)
         {
          return; 
         } 
          else
          {
           return;
          }
     }
       insert();


There are no spaces around your "WHERE" word. You're writing this :

"SELECT * FROM restaurantsWHEREcategory=" + cat

Just add spaces and it should be better.

By the way, using rawQuery is very slow because of the time used to parse your string. You should take a look at the NotePad app in the android SDK samples/ directory.


Three issues in your code:

  • Your function has a boolean return type, but in both cases of your if statement you return nothing. Perhaps you should try returning an appropriate boolean value?

  • You should be checking all sqlite operations for errors. Otherwise they will fail silently on you and your code will simply assume that there were no matching rows in the DB - if it gets that far without an error.

  • Building SQL queries by concatenating strings should be illegal. It is a very unsafe practice and it opens up your code to SQL injection attacks and the like. What would happen if your user entered "italian"; delete from restaurants in the cat text field? You should be using hosted parameters to guard against this.

EDIT:

As per LadaRaider's answer, you also seem to be missing a few spaces in your SQL query. Yet another reason not to concatenate strings to build it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜