Home > Database > Mysql Tutorial > How to Update a Specific Row in an Android SQLite Database Using `execSQL()` or `update()`?

How to Update a Specific Row in an Android SQLite Database Using `execSQL()` or `update()`?

Patricia Arquette
Release: 2025-01-12 16:50:43
Original
334 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template