Finds and then returns a user's reg_id from database - Android Database

Android examples for Database:SQL Query

Description

Finds and then returns a user's reg_id from database

Demo Code


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";
    /**//  ww w  . j a v a  2  s.  c o  m
     * Finds and then returns a user's reg_id. 
     * 
     * @param sqlConnection
     * An existing connection to the database. This method will make no attempt
     * to either open or close the connection.
     * 
     * @param userId
     * ID of the user that you want to find a reg_id for.
     * 
     * @return
     * Returns the regId of the user that you want as a String. If the user
     * could not be found, null is returned.
     * 
     * @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 String grabUsersRegId(final Connection sqlConnection,
            final long userId) throws SQLException {
        String regId = null;

        // prepare a SQL statement to be run on the database
        final String sqlStatementString = "SELECT "
                + TABLE_USERS_COLUMN_REG_ID + " FROM " + TABLE_USERS
                + " WHERE " + TABLE_USERS_COLUMN_ID + " = ?";
        final PreparedStatement sqlStatement = sqlConnection
                .prepareStatement(sqlStatementString);

        // prevent SQL injection by inserting data this way
        sqlStatement.setLong(1, userId);

        // run the SQL statement and acquire any return information
        final ResultSet sqlResult = sqlStatement.executeQuery();

        if (sqlResult.next())
        // user with specified id was found in the database
        {
            regId = sqlResult
                    .getString(DatabaseUtilities.TABLE_USERS_COLUMN_REG_ID);
        }

        closeSQLStatement(sqlStatement);

        return regId;
    }
    /**
     * 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) {

            }
        }
    }
}

Related Tutorials