JDBC and SQLJ

Java DataBase Connectivity (JDBC) is part of the Java Application Programming Interface. It is a set of Java commands to connect to and open databases. JDBC is related to ODBC (Open DataBase Connectivity) but has some advantages. JDBC is often much faster than ODBC, especially when the database itself is written in Java (such as is the case with Oracle).



Normally, SQL-statements (statements to query and manipulate a database) have to be declared in Java-Strings and are then send to the database using JDBC. There is however a faster and easier way to work with SQL in Java-programs: SQLJ.

SQL statements can simply be entered within the Java code, but have to start with a # .
The code is then passed through an interpreter which translates it to pure Java code. So the programmer does not have to write all the Java code him/her-selve, but this is done by the interpreter.



Example: Before SQLJ, you needed to write the following Java code:

// (Presume you already have a JDBC Connection object conn)
// Define Java variables
String name;
int id=37115;
float salary=20000;
// Set up JDBC prepared statement.
PreparedStatement pstmt = conn.prepareStatement ("select ename from emp where empno=? and sal>?");
pstmt.setInt(1, id);
pstmt.setFloat(2, salary);
// Execute query; retrieve name and
// assign it to Java variable.
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
name=rs.getString(1);
System.out.println("Name is: " + name);
}
// Close result set & statement objects
rs.close()
pstmt.close();


With SQLJ the programmer can simply replace it by:

String name;
int id=37115;
float salary=20000;
#sql {select ename into :name from emp where empno = :id and sal > :salary);
System.out.println("Name is: " + name);

So, SQLJ makes live much easier for the programmer.


Computer Chemistry Consultancy, June 2001