使用连接(和语句)
一旦我们获得了 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
}
}