在SQLite中更新数据,使用Update还是execSQL更合适?
Great question! Let’s break this down clearly to help you decide which approach makes sense for your work.
First, let’s compare the two methods you’re looking at:
execSQL(): This is a general-purpose method for running any SQL statement—great for DDL (likeCREATE TABLE) or DML operations that don’t need a return value (likeUPDATE/DELETE). The downsides? It doesn’t return the number of rows affected, and you have to write the full SQL string yourself (though using parameterized queries like your example avoids SQL injection risks).SQLiteDatabase.update(): This is Android’s purpose-built wrapper for update operations, and it’s the preferred choice for most cases:- It automatically constructs the
UPDATEstatement for you, cutting down on syntax errors from manual SQL writing - It returns the number of rows affected, so you can easily verify if your update worked
- It supports parameterized queries too, so no SQL injection risks here
- The code is more readable and aligns with Android’s recommended best practices
- It automatically constructs the
For best practices, go with SQLiteDatabase.update() for standard single-table updates. Here’s how you’d rewrite your example with it:
ContentValues values = new ContentValues(); values.put("COLOR", "RED"); int affectedRows = myDatabase.update( "FRUIT", values, "ID=?", new String[]{"7"} ); // Check if the update was successful if (affectedRows > 0) { Log.i(TAG, "Update succeeded! Rows affected: " + affectedRows); }
execSQL()? There are a few common reasons tutorials opt for execSQL():
- Teaching Fundamentals: It’s a more direct way to show raw SQL syntax, which helps new learners understand the underlying database logic before moving to wrapped methods. For someone just starting with SQLite, seeing the actual
UPDATEquery can clarify what’s happening under the hood. - Flexibility for Complex Scenarios: For more advanced updates (like multi-table joins or complex conditional logic),
execSQL()lets you write custom SQL that might be harder to replicate with theupdate()method’s structured parameters. - Simplicity for Examples: In quick demos,
execSQL()can feel more concise—you don’t need to create aContentValuesobject, so it’s faster to write and show a basic update action.
Use SQLiteDatabase.update() for everyday, straightforward updates—it’s safer, more readable, and gives you feedback on whether the operation worked. execSQL() is totally valid too, though, especially when you need to write complex custom SQL or want to demonstrate raw database syntax (just make sure you always use parameterized queries like your example to avoid SQL injection!).
内容的提问来源于stack exchange,提问作者Andressa Pinheiro

