1 Make sure a proper JDBC driver is loaded. The driver must be present in the project library as a jar file, such as ojdbc6.jar for Oracle | The following lines will load and register the driver: String driverName = "oracle.jdbc.driver.OracleDriver"; // for Oracle DB java.sql.Driver driver = (java.sql.Driver) Class.forName(driverName).newInstance(); // fails if ojdbc6.jar is not in the lib DriverManager.registerDriver(driver); |
2 Connect to a databaseUsing Oracle XE default connection URL | String connectionUrl = "jdbc:oracle:thin:@localhost:1521:xe"; // hostName=localhost; port=1521; DB instance=xe String user = "ITS"; // In the Oracle world, usually user is the name of a database to connect String password = "tiger"; Connection con = DriverManager.getConnection(connectionUrl, user, password); |
There are two types of statements: java.sql.Statement (a light version) and java.sql.PreparedStatement (a heavy version). PreparedStatement is slower to create, but is reusable and performing better when program repeats the same SQL many times. In the case of PreparedStatement we provide "?" instead of variable values and later replace "?" with run-time variables. PreparedStatement is commonly used in JDBC programs. | |
3 Example of using PreparedStatement | PreparedStatement pstmt = con.prepareStatement( "select NAME, SSN from PAYROLL where SSN = ?"); pstmt.setString(1, ssnVariable); // replacing the first (and only) "?" with ssnVariable |
4 Execute the statement pstmt.executeQuery(); // for SELECT pstmt.execute(); // for INSERT, etc. | // While executing a query, a program will get back java.sql.ResultSet from the database ResultSet rset = pstmt.executeQuery(); // ResultSet is a set of records retrieved by the query |
5 Processing the Result Set Getting specific data from the records retrieved by our program with the execute method. | // Check if ResultSet still not empty and get first column from the next string resultwhile (rset.next() ) { String aName = rset.getString( 1 ); String ssn = rset.getString( 2 ); System.out.println("Name is " + aName + " SSN is " + ssn); } |