【问题标题】:How to update the value of the existing columns in SQLite android ? (not able to do in my project)如何更新 SQLite android 中现有列的值? (不能在我的项目中做)
【发布时间】:2025-11-23 06:15:02
【问题描述】:

我正在尝试更新我的表的现有列,但我无法这样做.... 没有错误,只是没有更新。 我的代码在下面


通过传递值调用函数a是我要更改的_id,而i是我要插入的值。

     boolean isUpdate = mDbHelper.updatedata(String.valueOf(a),String.valueOf(i));

我用来改变值的函数


 public boolean updatedata(String id,String books){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put(Lib_student.COLUMN_STUDENT_BOOKS,books);

        Cursor cursor = db.rawQuery("select * from Library_Student where books=?",new String[]{books});
        
            long r = db.update("Library_Student",contentValues,"books=?",new String[]{books});
            if (r == -1){
                return false;
            }else {
                return true;
            }
            
    }

这是我需要编辑的表格..

    String SQL_CREATE_LIBRARY_TABLE_STUDENT = "CREATE TABLE "+ Lib_student.TABLE_NAME + " ("
                +Lib_student._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                +Lib_student.COLUMN_STUDENT_NAME+ " TEXT NOT NULL, "
                +Lib_student.COLUMN_STUDENT_EMAIL+ " TEXT, "
                +Lib_student.COLUMN_STUDENT_AGE+ " INTEGER , "
                +Lib_student.COLUMN_STUDENT_GENDER+ " TEXT ,"
                +Lib_student.COLUMN_STUDENT_NUMBER+ " INTEGER ,"
                +Lib_student.COLUMN_STUDENT_ADDRESS+ " TEXT ,"
                +Lib_student.COLUMN_STUDENT_BOOKS + " INTEGER );";

【问题讨论】:

    标签: java android sqlite sql-update android-sqlite


    【解决方案1】:

    首先,不需要选择要更新的行,因此删除此行:

    Cursor cursor = db.rawQuery("select * from Library_Student where books=?",new String[]{books});
    

    此外,您必须将 id 而不是 books 的值作为参数传递给方法 update()

    public boolean updatedata(String id, String books) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(Lib_student.COLUMN_STUDENT_BOOKS, books);
        return db.update("Library_Student", contentValues, Lib_student._ID + " = ?", new String[]{id}) > 0;
    }
    

    update() 方法返回更新的行数(它从不返回-1),因此您必须将该数字与0 进行比较,如果大于0 或@987654332,则返回true @如果是0

    【讨论】:

    • 有什么方法可以在表格中添加值而不是像我们为 textViews 设置 .append 那样替换它?
    • @Amelia 如果要插入新行,则需要方法 insert():*.com/questions/15006291/…
    最近更新 更多