使用連線(和語句)

一旦我們獲得了 Connection,我們將主要用它來建立 Statement 物件。Statements 代表單個 SQL 事務; 它們用於執行查詢,並檢索結果(如果有的話)。我們來看一些例子:

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
    }

}