Using the Connection (And Statements)

Download jdbc eBook

Example

Once we've gotten the Connection, we will mostly use it to create Statement objects. Statements represent a single SQL transaction; they are used to execute a query, and retrieve the results (if any). Let's look at some examples:

public void useConnection() throws SQLException{


    Connection conn = getConnection();

    //We can use our Connection to create Statements
    Statement state = conn.getStatement();

    //Statements are most useful for static, "one-off" queries
    
    String query = "SELECT * FROM mainTable";
    boolean sucess = state.execute(query);
    
    //The execute method does exactly that; it executes the provided SQL statement, and returns true if the execution provided results (i.e. was a SELECT) and false otherwise.

    ResultSet results = state.getResultSet();
    
    //The ResultSet object represents the results, if any, of an SQL statement.
    //In this case, the ResultSet contains the return value from our query statement.
    //A later example will examine ResultSets in more detail.

    ResultSet newResults = state.executeQuery(query)
    
    //The executeQuery method is a 'shortcut' method. It combines the execute and getResultSet methods into a single step.
    //Note that the provided SQL query must be able to return results; typically, it is a single static SELECT statement.
    //There are a number of similar 'shortcut' methods provided by the Statement interface, including executeUpdate and executeBatch

    //Statements, while useful, are not always the best choice. 
    
    String newQuery = "SELECT * FROM mainTable WHERE id=?";
    PreparedStatement prepStatement = conn.prepareStatement(newQuery);

    //PreparedStatements are the prefed alternative for variable statements, especially ones that are going to be executed multiple times

    for(int id:this.ids){

        prepStatement.setInt(1,id);
        //PreparedStatements allow you to set bind variables with a wide variety of set methods.
        //The first argument to any of the various set methods is the index of the bind variable you want to set. Note that this starts from 1, not 0. 

        ResultSet tempResults = prepStatement.executeQuery()
        //Just like Statements, PreparedStatements have a couple of shortcut methods. 
        //Unlike Statements, PreparedStatements do not not take a query string as an argument to any of their execute methods.
        //The statement that is executed is always the one passed to the Connector.prepareStatement call that created the PreparedStatement
    }

}

Stats

Contributors: 2
2016-07-23
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook