更新数据库android没有用

时间:2016-02-20 17:53:38

标签: android sqlite android-sqlite

我在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)

QUANTITY NEXT:0(id:1)

所以某处出现了错误。你能告诉我代码是否合适吗?特别是这一个:

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

这意味着在id = 1时数量设置为1,不是吗? 我尝试UPDATE,我有相同的结果......

2 个答案:

答案 0 :(得分:0)

在调用第二个raw之前读取并关闭游标,因为没有它就不会执行查询:

Process p=Runtime.getRuntime().exec("something command"); 

String s;

JFrame frame = new JFrame();
frame.setSize(600, 400);
JTextField A = new JTextField();
A.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent e) {
    String s = A.getText();
    System.out.println("I send a text: " + s);
    try{
         p.getOutputStream().write(s.getBytes());
         p.getOutputStream().close();
    }catch(Exception ex){
        ex.printStackTrace();
    }
    A.setText("");
}    
});
frame.add(A);
frame.setVisible(true);


// Read command standard input
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
   System.out.println(s);
}

答案 1 :(得分: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;
很多

所以,有三种方法可以改变数据库:

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!

相关问题