JDBC Dr Jim Briggs
WEBP JDBC2 JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets) to databases Largely database independent –Requires SQL
WEBP JDBC3 JDBC architecture
WEBP JDBC4 Using JDBC Obtaining drivers Making a connection Executing a command –Statements –Result sets
WEBP JDBC5 Obtaining drivers Usually provided (free) by database vendors Common ones –oracle.jdbc.driver.OracleDriver –com.mysql.jdbc.Driver –sun.jdbc.odbc.JdbcOdbcDriver Need to download and install –In a webapp, put the Jar file in WEB-INF/lib
WEBP JDBC6 Connecting to a database Via a DriverManager (old) –Class.forName(DriverClassName).newInstance(); –Connection con = DriverManager.getConnection(URL,Username,Password); Via a DataSource (new) –Create DataSource object in configuration, e.g. in Tomcat’s context.xml file in an application server's environment
WEBP JDBC7 Connection URLs JDBC has a special form of URL Define location of database and access parameters in a driver-specific way Examples: –jdbc:mysql://localhost:3306/JIM
WEBP JDBC8 Doing a query Statement stmt = conn.createStatement(); ResultSet result = stmt.executeQuery( "SELECT Entry, Customer, DOW, Cups, Type " + "FROM JJJJData " + "ORDER BY Cups DESC“ ); while(result.next()) { out.println(result.getString(1)); out.println(result.getInt(“Cups”); }
WEBP JDBC9 Further features Prepared statements Bind variables Transactions
WEBP JDBC10 JDBC and web applications Special considerations –Connection latency –Connection pooling –Multiple connections –One connection per thread (request) –One transaction per request (normally)