Android examples for Database:Table Update
Updates a given user's registration Id in the database.
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Main{ public final static String TABLE_USERS = "users"; public final static String TABLE_USERS_COLUMN_ID = "id"; public final static String TABLE_USERS_COLUMN_REG_ID = "reg_id"; /**// w w w . ja va 2 s . co m * Updates a given user's regId in the database. This just replaces the * currently existing regId value with the regId value that you specify * here. If the specified regId is null then the user's regId will just be * removed. * * @param sqlConnection * An existing connection to the database. This method will make no attempt * to either open or close the connection. * * @param userId * The user ID of the user's who's regId needs to be updated. * * @param regId * The given user's new regId. Set this to null if you want the user's * regId to be removed. * * @throws SQLException * If at some point there is some kind of connection error or query problem * with the SQL database then this Exception will be thrown. */ public static void updateUserRegId(final Connection sqlConnection, final long userId, final String regId) throws SQLException { PreparedStatement sqlStatement = null; if (Utilities.verifyValidString(regId)) { // prepare a SQL statement to be run on the database final String sqlStatementString = "UPDATE " + TABLE_USERS + " SET " + TABLE_USERS_COLUMN_REG_ID + " = ? WHERE " + TABLE_USERS_COLUMN_ID + " = ?"; sqlStatement = sqlConnection .prepareStatement(sqlStatementString); // prevent SQL injection by inserting user data this way sqlStatement.setString(1, regId); sqlStatement.setLong(2, userId); } else { // prepare a SQL statement to be run on the database final String sqlStatementString = "UPDATE " + TABLE_USERS + " SET " + TABLE_USERS_COLUMN_REG_ID + " = null WHERE " + TABLE_USERS_COLUMN_ID + " = ?"; sqlStatement = sqlConnection .prepareStatement(sqlStatementString); // prevent SQL injection by inserting user data this way sqlStatement.setLong(1, userId); } // run the SQL statement sqlStatement.executeUpdate(); closeSQLStatement(sqlStatement); } /** * Releases a SQL PreparedStatement resource. * * @parameter sqlStatement * A SQL PreparedStatement object. It's okay if this object is null or if * it was never given an actual SQL statement / query to run. */ public static void closeSQLStatement( final PreparedStatement sqlStatement) { if (sqlStatement != null) { try { sqlStatement.close(); } catch (final SQLException e) { } } } }