|
4.1 Databases and JDBC
4.1.1 Getting things set upWhat you need to get started:
4.1.2 Connecting to the database
4.1.2.1 Load the driver
4.1.2.2 Create the connection
4.1.3 Statements
4.1.4 getXXX methodsWith ResultSet objects:
4.1.5 Updating the databaseUse executeUpdate when using SQL UPDATE commands:String update = "UPDATE user SET password='bar' WHERE user='foo'"; stmt.executeUpdate(update);
4.1.6 PreparedStatements
4.1.7 A real methodThe following method was copied from a production software application. Note that it uses a PreparedStatement for the syntactical ease of use that the PreparedStatement offers.
public String getPurchaserEmailAddress(int orderId) throws SQLException { Connection connection = null; try { String email = null; connection = ConnectionPool.getConnection(); String query = "SELECT email FROM orders WHERE order_id = ?"; PreparedStatement emailQuery = connection.prepareStatement(query); emailQuery.setInt(1, orderId); ResultSet rs = emailQuery.executeQuery(); if ( rs.next() ) { email = rs.getString(1); } return email; } finally { ConnectionPool.freeConnection(connection); } }
|
|