Query the database for a user's info. - Android Database

Android examples for Database:SQL Query

Description

Query the database for a user's info.

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";

    /**/*from   www.java  2s.co  m*/
     * Query the database for a user's info.
     * 
     * @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.
     * 
     * @return
     * The query's resulting ResultSet object. Could be empty or even null,
     * check for that and then the emptyness with the ResultSet's .next()
     * method.
     * 
     * @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 ResultSet grabUsersInfo(final Connection sqlConnection,
            final long userId) throws SQLException {
        // prepare a SQL statement to be run on the database
        final String sqlStatementString = "SELECT * 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();

        return sqlResult;
    }
}

Related Tutorials