Query the database for a user who's ID matches the input's. - Android Database

Android examples for Database:SQL Query

Description

Query the database for a user who's ID matches the input's.

Demo Code


//package com.book2s;
import java.sql.Connection;

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_NAME = "name";

    /**/*w w  w  . j  a va2s. c  o  m*/
     * Query the database for a user who's ID matches the input's.
     * 
     * @param sqlConnection
     * Your existing database Connection object. Must already be connected, as
     * this method makes no attempt at doing so.
     * 
     * @param userId
     * The ID of the user you're searching for as a long.
     * 
     * @return
     * The name of the user that you queried for as a String. If the user could
     * not be found then this method will return null.
     * 
     * @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 grabUsersName(final Connection sqlConnection,
            final long userId) throws SQLException {
        String username = null;

        // prepare a SQL statement to be run on the MySQL database
        final String sqlStatementString = "SELECT "
                + TABLE_USERS_COLUMN_NAME + " 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())
        // check to see that we got some SQL return data
        {
            // grab the user's name from the SQL query
            username = sqlResult.getString(TABLE_USERS_COLUMN_NAME);
        }

        closeSQLStatement(sqlStatement);

        return username;
    }

    /**
     * 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