首次学习SQLite CRUD操作时更新数据遇'no such column: key_name'错误求助
Hey there! Let's break down and fix this issue you're hitting. The error message clearly says no such column: key_name because your update query is referencing a column that doesn't exist in your database table. Let's look at where the problem is:
The Root Cause
In your MyDbHandler class, you've defined constants for your column names (like key_name = "name"), which you correctly used when creating the table. But in the updateUserDetails method, you're using the string literal "key_name" instead of the actual constant variable key_name when adding values to ContentValues.
Your database table has columns named name, email, phone, but your update code is trying to set values for columns named key_name, key_email, key_phone—which don't exist!
Corrected Code for updateUserDetails
Here's the fixed version of your update method:
public boolean updateUserDetails(UserModel userModel){ SQLiteDatabase database = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); // Use the constant variables instead of string literals contentValues.put(key_name, userModel.getName()); contentValues.put(key_email, userModel.getEmail()); contentValues.put(key_phone, userModel.getPhone()); // Execute the update and check if it was successful int rowsAffected = database.update(key_table, contentValues, key_id + "=?", new String[] {userModel.getId()}); database.close(); // Don't forget to close the database! return rowsAffected > 0; // Return true only if at least one row was updated }
Additional Notes
- Why Uninstalling Didn't Work: The issue is a code logic error, not a cached database problem. Uninstalling removes the old database, but your code still tries to reference the wrong column names when creating the new database connection—so the error persists.
- Improve
onUpgrade: Right now youronUpgrademethod is empty. If you ever need to modify your table structure later, you should add logic here to drop/recreate the table (or migrate data) to avoid similar issues. For example:@Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { // Drop older table if exists sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + key_table); // Create tables again onCreate(sqLiteDatabase); }
That should resolve the SQLiteException you're seeing. Give it a try!
内容的提问来源于stack exchange,提问作者Amit Kumar

