2016-02-20 86 views
0

我正在发现Android中的数据库。我了解如何阅读,但我没有成功写作。这里是数据库:更新数据库android不起作用

 private static final String DATABASE_CREATE = "create table lesPlats 
      (id integer primary key autoincrement, nom text not null, quantite integer);"; 
     database.execSQL(DATABASE_CREATE); 

我编辑:

 values.put("nom", "plat1"); 
     values.put("quantite", 0); 
     database.insert("lesPlats", null, values); 

我想提高 “plat1” 的数量(调试版本注释):

 int n=1; 
    // Cursor c = database.rawQuery("SELECT * FROM lesPlats WHERE id="+n, null); 
    // c.moveToFirst(); 
    // System.out.println("QUANTITY BEFORE: "+cursorToComment(c).quantite+ " (id: "+cursorToComment(c).id+")"); 

     database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null); 

    // c = database.rawQuery("SELECT * FROM lesPlats WHERE id="+n, null); 
    // c.moveToFirst(); 
    // System.out.println("QUANTITY NEXT: "+cursorToComment(c).quantite+ " (id: "+cursorToComment(c).id+")"); 

与调试,我得到结果

QUANTITY BEFORE:0(id:1)

数量下一个:0(id:1)

所以在某个地方有一个错误。你能告诉我代码是否好?特别这一个:

database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null);

这意味着量是在ID = 1设置为1,是吗? 我尝试更新,我有同样的结果...

+0

我忘了描述存储在数据库中的类:public class Comment { public long id; public String nom; public int quantite; –

+0

不重要,你的问题是重复的。查看该帖子中的解决方案。 –

+0

虽然,你真的不应该使用rawQuery ...看到这里的更好的解决方案http://stackoverflow.com/q/3760774/2308683 –

回答

0

读取并调用第二胎之前关闭游标,因为查询不会得到没有它执行:

c = database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null); 
c.moveToFirst(); 
c.close(); 
+0

中所述我尝试使用您的代码和database.execSQL(“UPDATE lesPlats SET quantite = 1 WHERE id =”+ n);但我没有改变... –

0

对不起你们,我已经忘了cursorToComment过程中的设置数量...

private Comment cursorToComment(Cursor cursor) { 
    Comment comment = new Comment(); 
    comment.setId(cursor.getLong(0)); 
    comment.setNom(cursor.getString(1)); 
    comment.setQqte(cursor.getInt(2)); //here!! 
    return comment; 

THX很多

因此,三种方式更改数据库:

ContentValues values = new ContentValues(); 
values.put("quantite", 1); 
database.update("lesPlats", values, "id=?", new String[]{"1"}); 

database.execSQL("UPDATE lesPlats SET quantite = 1 WHERE id = " + n); 

c = database.rawQuery("UPDATE lesPlats SET quantite = 1 WHERE id = " + n, null); 
c.moveToFirst(); 
c.close(); 

pfiou!