Você está na página 1de 5

Connecting InterBase to Java applications

To connect to an InterBase database from a Java program we need a driver that is able to communicate with the two parts. One standard way is to use the JDBC protocol. The latest version is JDBC2 which should be installed as part of the SDK (Software Development Kit) if you're using version 1.4 or later. Borland followed a different track than other DBMS suppliers. To make it faster to download when using applets they split the driver into two parts. One part (InterServer) would run as a server on the same computer holding the InterBase DBMS, the other part (InterClient) would be downloaded on the client running the Java program (or applet). The communication goes from the Java program to InterClient which is connected to the InterServer that finally communicates with the InterBase server. The advantage is that only a small part of the driver needs to be installed on the client. But as we're running the open source version of InterBase which is not able to run across networks there is no obvious advantages on the contrary: we need to install everything on the same computer which then must run two servers (InterBase and InterServer). To avoid this overhead we'll instead use another driver supplied by IBPhoenix. IBPhoenix has developed an open source database named Firebird (based on the open source version of InterBase). They also developed a JDBC-driver, named JayBird, that doesn't need the InterServer. JayBird works together with both Firebird and InterBase. It is this JayBird driver we'll describe in the following. For further information about Firebird and JayBird see www.IBPhoenix.com, for further information about InterServer/InterClient see www.Borland.com.

Getting and installing the driver At the moment the driver can be downloaded from: http://www.ibphoenix.com/main.nfs?a=ibphoenix&s=1083759433:151919&page=ibp_download_jaybird What you get when downloading is actually an archive (zip-file) with documentation, source code and a number of jar-files containing the drivers (jar-files is also archives). Which one you should use depends on what you are going to use it for and what you have installed already (see the documentation for further details). After download you must uncompress the zip-file. In the following we'll use the jar-file firebirdsql-full.jar that includes everything needed for a traditional Java SDK installation. To make this jar-file available for all your Java programs there is (at least) two different strategies (assuming you're using Windows as operating system): 1. change the classpath so it includes the folder holding the jar-file 2. copy the jar-file to a location used by the JVM (Java Virtual Machine) Changing the classpath can be both dangerous and difficult you should only do it if you're sure of what you're doing. Remember to reboot your computer when changing the classpath. Copying the jar-file to a location used by the JVM means that you must know the installation folder for the JVM. Note that when the SDK is installed it has it's own internal JRE (Java Runtime Environment) with a JVM so you might have more than one JVM installed. In the following we'll focus only on the internal JVM used when you're developing Java programs using the SDK installation. If you don't know where the Java SDK is installed you should search for it. It will probably be on the C: drive in a folder called j2sdk1.x.y (x and y depends on the version you're using).

The folder is (probably) placed either directly in the root or in the default folder for programs (Program Files for English versions of Windows Programmer for Danish versions). In the installation folder you'll find the folder jre\lib\ext - copy the jar-file firebirdsql-full.jar into this folder. The following table shows possible paths to look for (assuming you're using version C:\j2sdk1.4.2_03\jre\lib\ext C:\Program Files\j2sdk1.4.2_03\jre\lib\ext C:\Programmer\j2sdk1.4.2_03\jre\lib\ext

Using the driver How JDBC works and details about the specific commands are topics beyond the scope of this note. We'll only present a few examples to show you the idea. If you want to learn more about JDBC look at one of the following web-sites or in various text-books. http://csajsp-chapters.corewebprogramming.com/CSAJSP-Chapter18.pdf http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html http://java.sun.com/developer/onlineTraining/Database/JDBCShortCourse/jdbc/jdbc.html In the following we assume that you have created a simple InterBase database and that it resides in c:\data\InterBaseTest\hotelAdm.gdb (using the usual user sysdba with password masterkey) and that the jar-file with the driver is copied to the jre\lib\ext folder. Also we assume that the following class exists it will be used in the following example: public class Guest { private int guestNo; private String name; private String address; public Guest(int guestNo, String name, String address) { this.guestNo = guestNo; this.name = name; this.address = address; }//Guest(int, String, String) public String toString() { return guestNo + "\t" + name + "\t" + address; }//toString() }//Guest The syntax for loading the driver is: Class.forName( <driver> ) and the syntax for the database URL is: protocol:[//host[:port]/]<database>. The name of the driver to load is org.firebirdsql.jdbc.FBDriver and the protocol used is jdbc:firebidsql. The host is localhost as we're running the InterBase server on the same computer as the Java-program (thus no port number is needed). So the driver can be loaded using: Class.forName(org.firebirdsql.jdbc.FBDriver); The connection to the database is made using: Connection conn = DriverManager.getConnection( jdbc:firebirdsql://localhost/c:\\data\\InterBaseTest\\hotelAdm.gdb, sysdba, masterkey ); Notice we use \\ to get one backslash in a Java string.

The following Java-program loads the driver, creates a connection and perform some basic SQL on the database the comments should be self-explaining: import java.sql.*; public class JDBCTest { //Connection to database private static Connection connection; //ResultSet used to store results in various methods private static ResultSet rs; //Statement used to store SQL-statement in various methods private static Statement statement;

private static void loadDriver() throws ClassNotFoundException { String driver = "org.firebirdsql.jdbc.FBDriver"; // load driver Class.forName(driver); }//loadDriver()

private static Connection getConnection() throws SQLException { String username = "sysdba"; String password = "masterkey"; String protocol = "jdbc:firebirdsql:"; String host = "//localhost/"; String file = "c:\\data\\InterBaseTest\\hotelAdm.gdb"; String databaseUrl = protocol + host + file; //get and return connection return DriverManager.getConnection(databaseUrl, username, password); }//getConnection()

private static void deleteGuest() { //remove guest just inserted try { int noOfRows = statement.executeUpdate("DELETE FROM guests WHERE guestNo = 100"); System.out.println("Deleted rows (should be 1): " + noOfRows + "\n"); } catch(SQLException sqle) { System.out.println(sqle + "\nProgram exits"); System.exit(0); }//try-catch }//deleteGuest()

private static void insertGuest() { try { //insert a guest - note: use \" to get a " in a String int noOfRows = statement.executeUpdate("INSERT INTO guests VALUES " + "(100, 'Charlie Chaplin', 'Chaplin Home 123')"); System.out.println("Inserted rows (should be 1): " + noOfRows + "\n"); } catch(SQLException sqle) { System.out.println(sqle + "\nProgram exits"); System.exit(0); }//try-catch }//insertGuest()

private static void simpleSelect() { //get inf. about guests with GuestNo larger than 8: try { rs = statement.executeQuery("SELECT * FROM GUESTS WHERE GuestNo > 8"); //show inf. while (rs.next()) { int guestNo = rs.getInt("GuestNo"); String name = rs.getString("Name"); String address = rs.getString("Address"); System.out.println(guestNo + "\t" + name + "\t" + address); }//while rows in resultset System.out.println(); } catch(SQLException sqle) { System.out.println(sqle + "\nProgram exits"); System.exit(0); }//try-catch }//simpleSelect()

private static void makeObject() { //getting data for a guest and create Guest-object with them: try { rs = statement.executeQuery("SELECT * FROM Guests WHERE GuestNo = 9"); if (rs.next()) { int guestNo = rs.getInt(1); //we use columns number instead of name String name = rs.getString(2); String address = rs.getString(3); Guest g = new Guest(guestNo, name, address); System.out.println("Data from guest : " + g); }//if System.out.println(); } catch(SQLException sqle) { System.out.println(sqle + "\nProgram exits"); System.exit(0); }//try-catch }//makeObject()

private static void joinSelect() { //getting data from a join try { rs = statement.executeQuery( "SELECT * FROM Hotels h, Rooms r WHERE h.HotelNo = r.HotelNo " + "AND HotelNo BETWEEN 1 AND 3 AND r.RoomNo < 3"); //showing only some of the columns System.out.println("Hotel#\tName\t\tRoom#\tPrice"); while(rs.next()) { int hotelNo = rs.getInt("HotelNo"); String name = rs.getString("Name"); int roomNo = rs.getInt("RoomNo"); double price = rs.getDouble("Price"); System.out.println( hotelNo + "\t" + name + "\t" + roomNo + "\t" + price); }//while rows in resultset System.out.println(); } catch(SQLException sqle) { System.out.println(sqle + "\nProgram exits"); System.exit(0); }//try-catch }//joinSelect()

public static void main(String[] args) { //load driver try { loadDriver(); } catch (ClassNotFoundException cnfe) { System.out.println(cnfe + "\nProgram exits"); System.exit(0); }//try-catch

//get connection and create statement try { connection = getConnection(); //commits should be done explicitly: connection.setAutoCommit(false); //create a statement statement = connection.createStatement(); } catch(SQLException sqle) { System.out.println(sqle + "\nProgram exits"); System.exit(0); }//try-catch

//perform basic SQL statements on database insertGuest(); simpleSelect(); deleteGuest(); makeObject(); joinSelect();

//close connection try { connection.close(); } catch(SQLException sqle) { System.out.println(sqle + "\nProgram exits"); System.exit(0); }//try-catch }//main }//class JDBCTest