Home >Database >Mysql Tutorial >How to Update a Specific Row in an Android SQLite Database Using `execSQL()` or `update()`?
Modifying a Single Record in an Android SQLite Database
Android offers two main approaches for updating specific database rows: execSQL()
and update()
. The best choice depends on the complexity of your update operation.
For updating multiple fields using the update()
method, begin by constructing a ContentValues
object to hold the new values:
<code class="language-java">ContentValues values = new ContentValues(); values.put("Field1", "Bob"); // String value values.put("Field2", 19); // Integer value values.put("Field3", "Male"); // String value</code>
Next, execute the update using the update()
method. This requires the table name, the ContentValues
object, and a WHERE
clause to pinpoint the target row:
<code class="language-java">myDB.update(TableName, values, "_id = ?", new String[]{id});</code>
Here, "_id = ?" serves as the WHERE
clause, with id
representing the primary key of the row to modify. The "?" acts as a placeholder for the id
value, preventing SQL injection vulnerabilities.
For more intricate SQL updates, execSQL()
provides a direct route:
<code class="language-java">myDB.execSQL("UPDATE " + TableName + " SET Field1 = 'Bob', Field2 = 19, Field3 = 'Male' WHERE _id = 1");</code>
This approach directly executes a custom SQL statement. However, exercise caution, as it's more susceptible to SQL injection attacks compared to the update()
method. Use execSQL()
only when necessary, for updates beyond the capabilities of update()
.
The above is the detailed content of How to Update a Specific Row in an Android SQLite Database Using `execSQL()` or `update()`?. For more information, please follow other related articles on the PHP Chinese website!