1.1. Comparing SQLJ and JDBC

You may already be familiar with JDBC, another technology for adding SQL statements to a Java program. SQLJ operates at a higher level of abstraction and has a simpler, more concise syntax than JDBC. This results in SQLJ programs containing fewer lines of source code than comparable JDBC programs. Also unlike JDBC, SQLJ is strongly typed. With SQLJ, the compiler does more of the work for you because it checks your embedded SQL statements during compilation. JDBC checks your SQL statements only when you actually run your program. In short, SQLJ enables you to develop your programs more rapidly, more concisely, and with fewer mistakes than if you were to use JDBC.

To show you the power of SQLJ as compared to JDBC, the following two code snippets illustrate the use of each technology to perform the same task: retrieving the name and price of a product stored in a database. First, the JDBC code snippet:

int v_id = 1;
String v_name = null;
float v_price = 0.0;
PreparedStatement prepared_statement = connection.prepareStatement(
  "SELECT name, price FROM products WHERE id = ?"
);
prepared_statement.setInt(1, v_id);
ResultSet result_set = prepared_statement.executeQuery(  );
while (result_set.next(  )) {
  v_name = result_set.getString(1);
  v_price = result_set.getFloat(2);
  System.out.println("Name = " + v_name + ", price = " + v_price);
}
result_set.close(  );
prepared_statement.close(  )

Next, the SQLJ code snippet:

int v_id = 1; String v_name = null; float v_price ...

Get Java Programming with Oracle SQLJ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.