0

我需要在android的sql lite数据库中更新表callog.calls的列(cached_name)。我不知道如何使用更新语句。我无法使用cursor找到有关更新命令的任何信息。请帮助。提前致谢。

 //number1 is the phone number against which I need to run update query in db.
 //name is the string which I used to insert against number1..              

      String name=edittext.gettext().tostring();           
        ContentResolver cr = getContentResolver(); 
        Cursor cur = cr.query(CallLog.Calls.CONTENT_URI,
                    null, null, null, null);
        ContentValues value=new ContentValues();

        value.put("CallLog.Calls.CACHED_NAME",name);

        cur.moveToFirst();  
        while(!cur.isLast())
        {                   
              String number=cur.getString(cur.getColumnIndex(CallLog.Calls.NUMBER));                    
              if((number.equals(number1)==true)
              {  
                    try{                   
                         cr.update(CallLog.Calls.CONTENT_URI,value,CallLog.Calls.CACHED_NAME+"=?",null);
                    }
                    catch(Exception e)
                    {
                         e.printStackTrace();
                         System.out.println(e.getStackTrace()); 
                    }
             }//if  
             cur.moveToNext();   
        }//while
4

1 回答 1

0

基本上,您真正需要的唯一行是 update :

String name = edittext.getText().toString();
ContentResolver cr = getContentResolver(); 

ContentValues value = new ContentValues();
// Note that there is no "" here. The value is a constant
value.put(CallLog.Calls.CACHED_NAME, name);

cr.update(CallLog.Calls.CONTENT_URI, values, CallLog.Calls.NUMBER+"=?",
    new String[] { number1 });

这相当于这个原始 SQL 查询:

UPDATE call_log SET cached_name = name WHERE number = number1;

不需要遍历所有调用,这就是 where 子句的用途。

还,

while(!cur.isLast())

阻止您实际读取最后一个匹配值。不要那样做。利用

while (cur.moveToNext())

当您需要遍历游标时(此处不需要)

我强烈建议你看看游标是如何工作的,以及 sql 是如何工作的。

(另外,出于好奇,为什么需要修改callLog表?)

于 2011-11-30T13:17:14.947 回答