|
Subsections
What you need to get started:
- Java JDK (and JDBC).
- JDBC driver for your database.
- A database server (Oracle, Informix, DB2, Postgres, etc.).
- Create the database and tables you want to use.
- Class.forName("jdbc.DriverXYZ");
- Class.forName("org.postgresql.Driver");
- Connection conn = DriverManager.getConnection(url,"loginID", "password");
- The URL:
- jdbc:postgresql:database
- jdbc:postgresql://host/database
- jdbc:postgresql://host:port/database
- A Statement object is used to send an SQL statement to the DBMS.
- Create a Statement object and then execute it, using the proper execute method:
- For SELECT statements use executeQuery.
- For statements that create or modify tables use executeUpdate.
- Example:
Statement stmt = conn.createStatement();
String query = "SELECT username, password FROM user";
ResultSet rs = stmt.executeQuery(query);
while ( rs.next() )
{
String user = rs.getString("username");
String password = rs.getString("password");
System.out.println( "Username: " + user );
System.out.println( "Password: " + password );
}
With ResultSet objects:
- getByte
- getShort
- getInt
- getLong
- getFloat
- getDouble
- getBigDecimal
- getBoolean
- getString
- getBytes
- getDate
- getTime
- getTimestamp
- getAsciiStream
- getUnicodeStream
- getBinaryStream
- getObject
Use executeUpdate when using SQL UPDATE commands:
String update = "UPDATE user SET password='bar' WHERE user='foo'";
stmt.executeUpdate(update);
The 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);
}
}
|
|