SlideShare a Scribd company logo
1 of 35
Download to read offline
Ā© 2010 Marty Hall
Database Access
with JDBCOriginals of Slides and Source Code for Examples:Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/msajsp.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Ā© 2010 Marty Hall
For live Java EE training, please see training courses
at http://courses.coreservlets.com/.at http://courses.coreservlets.com/.
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP and this tutorial Available at public
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Servlets and JSP, and this tutorial. Available at public
venues, or customized versions can be held on-site at your
organization. Contact hall@coreservlets.com for details.
Overview
ā€¢ Overview of JDBC technology
ā€¢ JDBC design strategies
ā€¢ Using Apache Derby (Java DB)
ā€¢ Seven basic steps in using JDBC
ā€¢ Using JDBC from desktop Java apps
ā€¢ Using JDBC from Web apps
ā€¢ Prepared statements (parameterized
d )commands)
ā€¢ Meta data
Transaction controlā€¢ Transaction control
5
Ā© 2010 Marty Hall
Overview
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
JDBC Introduction
ā€¢ JDBC provides a standard library for
i l i l d baccessing relational databases
ā€“ API standardizes
ā€¢ Way to establish connection to databaseā€¢ Way to establish connection to database
ā€¢ Approach to initiating queries
ā€¢ Method to create stored (parameterized) queries
Th d t t t f lt (t bl )ā€¢ The data structure of query result (table)
ā€“ Determining the number of columns
ā€“ Looking up metadata, etc.
ā€“ API does not standardize SQL syntax
ā€¢ JDBC is not embedded SQL
ā€“ JDBC classes are in the java.sql packageJDBC classes are in the java.sql package
ā€¢ Note: JDBC is not officially an acronym;
ā€“ Unofficially, ā€œJava DataBase Connectivityā€ is commonly used7
On-line Resources
ā€¢ Sunā€™s JDBC Site
ā€“ http://java.sun.com/javase/6/docs/technotes/guides/jdbc/
ā€¢ JDBC Tutorial
h //j /d /b k / i l/jdb /ā€“ http://java.sun.com/docs/books/tutorial/jdbc/
ā€¢ API for java.sql
http://java sun com/javase/6/docs/api/java/sql/ā€“ http://java.sun.com/javase/6/docs/api/java/sql/
package-summary.html
ā€¢ List of Available JDBC Drivers
ā€“ http://developers.sun.com/product/jdbc/drivers
ā€¢ Or, just look in your database vendorā€™s documentation
8
JDBC Drivers
ā€¢ JDBC consists of two parts:
ā€“ JDBC API, a purely
Java-based API
ā€“ JDBC Driver Manager which
Java Application
JDBC API
ā€“ JDBC Driver Manager,which
communicates with
vendor-specific drivers that
f th l i ti
JDBC Driver Manager
JDBC Driver API
perform the real communication
with the database.
ā€¢ Point: translation to vendor
Vendor Specific
JDBC Driver
JDBC-ODBC
Bridge
format is performed on
the client
ā€“ No changes needed
t
Vendor Specific
ODBC Driver
Database
to server
ā€“ Driver (translator) needed
on client
9
Database
JDBC Data Types
JDBC Type Java TypeJDBC Type Java Type
BIT boolean
TINYINT byte
SMALLINT short
INTEGER intINTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE
JDBC Type Java Type
NUMERIC BigDecimal
DECIMAL
DATE java sql DateDOUBLE
BINARY byte[]
VARBINARY
LONGVARBINARY
CHAR String
DATE java.sql.Date
TIME java.sql.Timestamp
TIMESTAMP
CLOB Clob
BLOB Blob
VARCHAR
LONGVARCHAR
BLOB Blob
ARRAY Array
DISTINCT mapping of underlying type
STRUCT Struct
REF Ref
10
REF Ref
JAVA_OBJECT underlying Java class
Ā© 2010 Marty Hall
Steps for Using JDBC
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
JDBC Design Strategies
ā€¢ In general, plan for changes to data access
ā€“ Limit the data access to single area of code
ā€¢ Donā€™t distribute JDBC calls throughout the code
ā€¢ Plan ahead for changing from JDBC to Hibernate orPlan ahead for changing from JDBC to Hibernate or
another tool
ā€“ Donā€™t return JDBC-specific (or Hibernate-specific)
objects from the data access layerobjects from the data-access layer
ā€¢ Return ordinary Java objects instead
ā€¢ In JDBC, plan for changes, p g
ā€“ Limit the definition of driver, URL, etc. to single location
ā€¢ Let database experts do their stuff
ā€“ If database is complex, let database expert design the
database and design the queries
12
Seven Basic Steps in
Using JDBCUsing JDBC
1. Load the driver
ā€“ Not required in Java 6, so Java 6 needs only 6 steps.
2. Define the Connection URL
3 E t bli h th C ti3. Establish the Connection
4. Create a Statement object
5 E t5. Execute a query
6. Process the results
7 Cl th ti7. Close the connection
13
JDBC Step 1: Load the Driver
ā€¢ Not required in Java 6
ā€“ In Java SE 6.0 and later (JDBC 4.0 and later), the driver
is loaded automatically.
ā€¢ Java 5 and earlierā€¢ Java 5 and earlier
ā€“ Load the driver class only. The class has a static
initialization block that makes an instance and registers itg
with the DriverManager.
try {
Class.forName("com.mysql.jdbc.Driver");
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " cnfe);
}
14
JDBC Step 2: Define the
Connection URLConnection URL
ā€¢ Remote databases
F t i ā€œjdb d N ā€ā€“ Format is ā€œjdbc:vendorName:ā€¦ā€
ā€¢ Address contains hostname, port, and database name
ā€¢ Exact details given by supplier of JDBC driver
ā€¢ Embedded Derby databaseā€¢ Embedded Derby database
ā€“ The ā€œJava DBā€ (i.e., Apache Derby) is bundled with Java 6
and can be used for a database embedded in the same Java VM
that runs the app serverthat runs the app server.
ā€“ Format is ā€œjdbc:derby:databaseNameā€
ā€¢ Examples
String host = "dbhost.yourcompany.com";
String dbName = "someName";
int port = 1234;
String mySqlUrl = "jdbc:mysql//" + host + ":" + port +g y q j y q p
"/" + dbName;
String embeddedDerbyUrl = "jdbc:derby" + dbName;
15
JDBC Step 3: Establish the
ConnectionConnection
ā€¢ Get the main connection
Properties userInfo = new Properties();
userInfo.put("user", "jay_debesee");
userInfo.put("password", "secret");
Connection connection =
DriverManager.getConnection(mySqlUrl, userInfo);
ā€¢ Optionally, look up info about the databasep y, p
DatabaseMetaData dbMetaData =
connection.getMetaData();
String productName =g p
dbMetaData.getDatabaseProductName();
System.out.println("Database: " + productName);
String productVersion =g p
dbMetaData.getDatabaseProductVersion();
System.out.println("Version: " + productVersion);
16
JDBC Step 4: Make a Statement
ā€¢ Idea
ā€“ A Statement is used to send queries or commands
ā€¢ Statement types
S P dS C ll bl Sā€“ Statement, PreparedStatement, CallableStatement
ā€¢ Details on other types given later
ā€¢ ExampleExample
Statement statement =
connection.createStatement();
17
JDBC Step 5: Execute a Query
ā€¢ Idea
ā€“ statement.executeQuery("SELECT ā€¦ FROM ā€¦");
ā€¢ This version returns a ResultSet
ā€“ statement executeUpdate("UPDATE ");ā€“ statement.executeUpdate( UPDATE ā€¦ );
ā€“ statement.executeUpdate("INSERT ā€¦");
ā€“ statement.executeUpdate("DELETEā€¦");
ā€“ statement.execute("CREATE TABLEā€¦");
ā€“ statement.execute("DROP TABLE ā€¦");
E lā€¢ Example
String query =
"SELECT col1, col2, col3 FROM sometable";
ResultSet resultSet =
statement.executeQuery(query);
18
JDBC Step 6: Process the
ResultResult
ā€¢ Important ResultSet methods
ā€“ resultSet.next()
ā€¢ Goes to the next row. Returns false if no next row.
ā€“ resultSet getString("columnName")ā€“ resultSet.getString( columnName )
ā€¢ Returns value of column with designated name in current
row, as a String. Also getInt, getDouble, getBlob, etc.
ltS t tSt i ( l I d )ā€“ resultSet.getString(columnIndex)
ā€¢ Returns value of designated column. First index is 1 (ala
SQL), not 0 (ala Java).
ā€“ resultSet.beforeFirst()
ā€¢ Moves cursor before first row, as it was initially. Also first
ā€“ resultSet absolute(rowNum)resultSet.absolute(rowNum)
ā€¢ Moves cursor to given row (starting with 1). Also last and
afterLast.
19
JDBC Step 6: Process the
ResultResult
ā€¢ Assumption
ā€“ Query was ā€œSELECT first, last, address FROMā€¦ā€
ā€¢ Using column names
while(resultSet next()) {while(resultSet.next()) {
System.out.printf(
"First name: %s, last name: %s, address: %s%n",
resultSet.getString("first"),
resultSet.getString("last"),
resultSet.getString("address"));
}
U i l i diā€¢ Using column indices
while(resultSet.next()) {
System.out.printf(
"First name: %s last name: %s address: %s%n""First name: %s, last name: %s, address: %s%n",
resultSet.getString(1),
resultSet.getString(2),
resultSet.getString(3)); }20
JDBC Step 7: Close the
ConnectionConnection
ā€¢ Idea
ā€“ When totally done, close the database connection.
However, opening a new connection is typically much
more expensive than sending queries on existingmore expensive than sending queries on existing
connections, so postpone this step as long as possible.
ā€“ Many JDBC drivers do automatic connection pooling
h l li i i l ili iā€“ There are also many explicit connection pool utilities
ā€¢ Example
connection close();connection.close();
21
Ā© 2010 Marty Hall
Using Apache Derby
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Apache Derby: Overview
ā€¢ Overview
ā€“ Written in Java. Good for small/medium applications
(less than gigabyte database size, few queries/second)
ā€“ Bundled with Java 6 but latest version can beā€“ Bundled with Java 6, but latest version can be
downloaded from Apache for Java 1.4 and later.
ā€¢ Embedded mode
ā€“ Database runs in same VM as Java app. Does not accept
network connections.
Perfect for Web appsā€“ Perfect for Web apps
ā€¢ Incredibly easy to set up. Just drop in one JAR file
ā€¢ Good if database is accessed only from the Web apps
ā€¢ Standalone mode
ā€“ Runs in separate VM. Accepts network connections.23
Downloading and Installing
DerbyDerby
ā€¢ Downloading and documentation
http://db apache org/derby/ā€“ http://db.apache.org/derby/
ā€¢ Use in embedded mode
ā€“ Code
F W b d d b j i WEB INF/libā€¢ For Web apps, drop derby.jar in WEB-INF/lib
ā€¢ For other apps, put derby.jar in CLASSPATH
ā€“ URL
ā€¢ jdbc:derby:databaseNamejdbc:derby:databaseName
ā€“ Driver class name
ā€¢ org.apache.derby.jdbc.EmbeddedDriver
ā€¢ Not needed in Java 6!
ā€“ Username/password
ā€¢ Any are legal since DB runs inside the application.
ā€¢ Use in standalone mode
ā€“ See http://db.apache.org/derby/papers/DerbyTut/
ā€“ Consider MySQL, Oracle, etc. as alternatives
24
Setup Summary
ā€¢ Setup summary
l d d l b f db h /d b /ā€“ Downloaded latest Derby ZIP from db.apache.org/derby/
ā€¢ db-derby-10.5.3.0-bin.zip, but any recent version is fine
ā€¢ You can also use version bundled with JDK 1.6.x
ā€“ Unzipped
ā€“ Put install_dir/lib/derby.jar into CLASSPATH
ā€¢ Many options in Eclipse but if you make a Dynamic Webā€¢ Many options in Eclipse, but if you make a Dynamic Web
Project, drop derby.jar in WebContent/WEB-INF/lib
ā€“ Thatā€™s it (for embedded usage)!
C thi 90 d t i t lli O lā€¢ Compare this 90 second process to installing Oracle
ā€¢ Creating database
ā€“ Can be created directly from Java using SQL commandsCan be created directly from Java using SQL commands
via JDBC. See later slides. Need to run creator code at
least once before accessing database.
25
Setup Details: Desktop Apps
ā€¢ Putting derby.jar in
CLASSPATHCLASSPATH
ā€“ R-click on project in Eclipse, create
new folder called ā€œlibā€. Put derby.jar
in libin lib.
ā€“ R-click on project. Properties ļƒ  Java
Build Path ļƒ  Libraries ļƒ  Add JARs
N i t t j t/lib/ d l tā€“ Navigate to project/lib/ and select
derby.jar. Press OK.
ā€¢ Creating database
ā€“ Manually run database creation code.
See ā€œPrepared Statementsā€ section for
code, but this needs to be done once
l I t l h tonly. In most real apps, you have to
query database, but someone else
creates the database.26
Setup Details: Web Apps
ā€¢ Putting derby.jar in CLASSPATH
ā€“ Copy derby.jar to WEB-INF/lib
ā€¢ Creating database
R d b i d S ā€œP d S ā€ā€“ Run database creation code. See ā€œPrepared Statementsā€
section for code . This needs to be done once only, so best
way is to do it automatically in ServletContextListener. Iny y
most real apps, you have to query database, but someone
else creates the database.
ā€¢ Reminder: full code can be downloaded fromReminder: full code can be downloaded from
http://courses.coreservlets.com/Course-Materials/
msajsp.html, so you can get db creation code there.
27
Ā© 2010 Marty Hall
Using JDBC fromUsing JDBC from
Desktop Javap
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Approach
ā€¢ Same basic steps
ā€“ Load the driver
ā€“ Define the Connection URL
ā€“ Establish the ConnectionEstablish the Connection
ā€“ Create a Statement object
ā€“ Execute a query
ā€“ Process the results
ā€“ Close the connection
ā€¢ Differences from JDBC in Web appsā€¢ Differences from JDBC in Web apps
ā€“ Results are often put into Swing or AWT interfaces
ā€“ If you use value in calculation, use getInt, getDouble, etc.y , g , g ,
ā€“ If value is only used for display in GUI, you can use
getString even if value is another type
29
Sample Database
ā€¢ Table name
ā€“ employees
ā€¢ Column names
id (int) The employee IDā€“ id (int). The employee ID.
ā€“ firstname (varchar/String). Employeeā€™s given name.
ā€“ lastname (varchar/String). Employeeā€™s family name.
ā€“ position (varchar/String). Corporate position (eg, ā€œceoā€).
ā€“ salary (int). Yearly base salary.
ā€¢ Database nameā€¢ Database name
ā€“ myDatabase
ā€¢ Note
ā€“ See ā€œPrepared Statementsā€ section for code that created DB
30
Example:
Printing Employee InfoPrinting Employee Info
package coreservlets; The URL and the driver are the only parts that are specific to Derby. So, if you switch to MySql,
Oracle, etc., you have to change those two lines (or just one line in Java 6 with JDBC 4 driver,
since the driver no longer needs to be declared in that situation). The rest of the code is
import java.sql.*;
import java.util.*;
database independent.
public class ShowEmployees {
public static void main(String[] args) {
St i l "jdb d b D t b "String url = "jdbc:derby:myDatabase";
Properties userInfo = new Properties();
userInfo.put("user", "someuser");
( )userInfo.put("password", "somepassword");
String driver =
"org.apache.derby.jdbc.EmbeddedDriver";
showSalaries(url, userInfo, driver);
}
31
Example: Printing Employee
Info (Connecting to Database)Info (Connecting to Database)
public static void showSalaries(String url,
Properties userInfo,Properties userInfo,
String driverClass) {
try {
// Load the driver. NOT NEEDED in Java 6!
// Class.forName(driverClass);
// Establish network connection to database.
Connection connection =Connection connection =
DriverManager.getConnection(url, userInfo);
System.out.println("Employeesn==========");
// Create a statement for executing queries.
Statement statement = connection.createStatement();
String query =
"SELECT * FROM employees ORDER BY salary";
// S d t d t b d t lt// Send query to database and store results.
ResultSet resultSet = statement.executeQuery(query);
32
Example: Printing Employee
Info (Processing Results)Info (Processing Results)
while(resultSet.next()) {
int id = resultSet.getInt("id");int id resultSet.getInt( id );
String firstName = resultSet.getString("firstname");
String lastName = resultSet.getString("lastname");
String position = resultSet.getString("position");
int salary = resultSet.getInt("salary");
System.out.printf
("%s %s (%s, id=%s) earns $%,d per year.%n",
firstName lastName position id salary);firstName, lastName, position, id, salary);
}
connection.close();
} catch(Exception e) {
System.err.println("Error with connection: " + e);
}
33
Example: Printing Employee
Info (Output)Info (Output)
Employees
==========
Gary Grunt (Gofer, id=12) earns $7,777 per year.
Gabby Grunt (Gofer, id=13) earns $8,888 per year.
Cathy Coder (Peon, id=11) earns $18,944 per year.
Cody Coder (Peon, id=10) earns $19,842 per year.
Danielle Developer (Peon, id=9) earns $21,333 per year.
David Developer (Peon, id=8) earns $21,555 per year.
Joe Hacker (Peon, id=6) earns $23,456 per year.
Jane Hacker (Peon, id=7) earns $32,654 per year.
Keith Block (VP, id=4) earns $1,234,567 per year.
Thomas Kurian (VP id=5) earns $2 431 765 per yearThomas Kurian (VP, id=5) earns $2,431,765 per year.
Charles Phillips (President, id=2) earns $23,456,789 per year.
Safra Catz (President, id=3) earns $32,654,987 per year.
Larry Ellison (CEO, id=1) earns $1,234,567,890 per year.y ( , ) $ , , , p y
34
Ā© 2010 Marty Hall
Using JDBC fromUsing JDBC from
Web Appspp
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Approach
ā€¢ Same basic steps
L d h d iā€“ Load the driver
ā€“ Define the Connection URL
ā€“ Establish the Connection
ā€“ Create a Statement object
ā€“ Execute a query
Process the resultsā€“ Process the results
ā€“ Close the connection
ā€¢ Differences from JDBC in desktop appsp pp
ā€“ Results are often put into HTML
ā€“ If value is inserted directly into HTML, you can use
getString even if value is another typegetString even if value is another type
ā€“ To support concurrent access, you usually use a driver
that supports connection pooling
36
Sample Database
ā€¢ Table name
ā€“ employees
ā€¢ Column names
id (int) The employee IDā€“ id (int). The employee ID.
ā€“ firstname (varchar/String). Employeeā€™s given name.
ā€“ lastname (varchar/String). Employeeā€™s family name.
ā€“ position (varchar/String). Corporate position (eg, ā€œceoā€).
ā€“ salary (int). Yearly base salary.
ā€¢ Database nameā€¢ Database name
ā€“ myDatabase
ā€¢ Note
ā€“ See ā€œPrepared Statementsā€ section for code that created DB
37
A Servlet to Show Employee
InfoInfo
ā€¢ Overview
ā€“ Same sample database as before
ā€¢ DB type: Derby in embedded mode
ā€¢ DB name: employeesDB name: employees
ā€¢ Columns: id, firstname, lastname, position, salary
ā€¢ Goal
ā€“ Build HTML table that shows all employees
ā€¢ Approach
B ild HTML t bl di tl i l tā€“ Build HTML table directly in servlet
ā€¢ MVC combined with JSTL or custom tags might work
better, but this lecture does not assume familiarity with
th t ithose topics
ā€¢ Basic JDBC code is the same either way
38
Employee Info Servlet
public class EmployeeServlet1 extends HttpServlet {
//private final String driver//private final String driver =
// "org.apache.derby.jdbc.EmbeddedDriver";
protected final String url = "jdbc:derby:myDatabase";
protected final String tableName = "employees";
protected final String username = "someuser";
protected final String password = "somepassword";
The URL and the driver are the only parts that are specific to Derby. So, if you switch to MySql,
Oracle, etc., you have to change those two lines (or just one line in Java 6 with JDBC 4 driver,
39
Oracle, etc., you have to change those two lines (or just one line in Java 6 with JDBC 4 driver,
since the driver no longer needs to be declared in that situation). The rest of the code is
database independent.
Employee Info Servlet
(Continued)(Continued)
public void doGet(HttpServletRequest request,
HttpServletResponse response)p p p )
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " +
"Transitional//EN"n";
String title = "Company Employees";St g t t e Co pa y p oyees ;
out.print(docType +
"<HTML>n" +
"<HEAD><TITLE>" + title + "</TITLE></HEAD>n" +
/ / "<LINK REL='STYLESHEET' HREF='./css/styles.css'n" +
" TYPE='text/css'>" +
"<BODY><CENTER>n" +
"<TABLE CLASS='TITLE' BORDER='5'>" +<TABLE CLASS TITLE BORDER 5 > +
" <TR><TH>" + title + "</TABLE><P>");
showTable(out);
out.println("</CENTER></BODY></HTML>"); }40
Employee Info Servlet
(Continued)(Continued)
protected void showTable(PrintWriter out) {
try {try {
Connection connection = getConnection();
Statement statement = connection.createStatement();
String query = "SELECT * FROM " + tableName;String query = "SELECT * FROM " + tableName;
ResultSet resultSet = statement.executeQuery(query);
printTableTop(connection, resultSet, out);
i tT bl B d ( ltS t t)printTableBody(resultSet, out);
connection.close();
} catch(Exception e) {
S t i tl ("E " )System.err.println("Error: " + e);
}
}
41
Employee Info Servlet
(Continued)(Continued)
protected Connection getConnection()
throws Exception {throws Exception {
// Load database driver if it's not already loaded.
// Not needed in JDBC 4 (Java SE 6). Uncomment
// for earlier versions// for earlier versions.
// Class.forName(driver);
// E t bli h t k ti t d t b// Establish network connection to database.
Properties userInfo = new Properties();
userInfo.put("user", username);
I f t(" d" d)userInfo.put("password", password);
Connection connection =
DriverManager.getConnection(url, userInfo);
return(connection);
}
42
Employee Info Servlet
(Continued)(Continued)
protected void printTableTop(Connection connection,
ResultSet resultSetResultSet resultSet,
PrintWriter out)
throws SQLException {
out.println("<TABLE BORDER='1'>");out.println( <TABLE BORDER 1 > );
// Print headings from explicit heading names
String[] headingNames =
{ "ID", "First Name", "Last Name",{ , , ,
"Position", "Salary" };
out.print("<TR>");
for (String headingName : headingNames) {g g g
out.printf("<TH>%s", headingName);
}
out.println();
}
43
Employee Info Servlet
(Continued)(Continued)
protected void printTableBody(ResultSet resultSet,
PrintWriter out)PrintWriter out)
throws SQLException {
// Step through each row in the result set and print cells
while(resultSet.next()) {
out.println("<TR ALIGN='RIGHT'>");
out.printf(" <TD>%d", resultSet.getInt("id"));
out.printf(" <TD>%s", resultSet.getString("firstname"));
out.printf(" <TD>%s", resultSet.getString("lastname"));
out.printf(" <TD>%s", resultSet.getString("position"));
out.printf(" <TD>$%,d%n", resultSet.getInt("salary"));
}}
out.println("</TABLE>");
}
}}
44
Employee Info Servlet (Results)
45
Ā© 2010 Marty Hall
Using MetaData
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Using MetaData
ā€¢ Idea
ā€“ For most queries, you know column names and database
version ahead of time. But you can discover this
dynamically as well.dynamically as well.
ā€¢ System-wide data
ā€“ connection.getMetaData().getDatabaseProductName()g () g ()
ā€“ connection.getMetaData().getDatabaseProductVersion()
ā€¢ Table-specific data
ā€“ resultSet.getMetaData().getColumnCount()
ā€¢ When using the result, remember that
the index starts at 1, not 0
ā€“ resultSet.getMetaData().getColumnName()
47
Using MetaData: Example
public class EmployeeServlet2 extends EmployeeServlet1 {
protected void printTableTop(Connection connectionprotected void printTableTop(Connection connection,
ResultSet resultSet,
PrintWriter out)
throws SQLException {throws SQLException {
// Look up info about the database as a whole.
DatabaseMetaData dbMetaData = connection.getMetaData();
String productName =g p
dbMetaData.getDatabaseProductName();
String productVersion =
dbMetaData.getDatabaseProductVersion();g
out.println("<UL>n" +
" <LI><B>Database:</B>n" + productName +
" <LI><B>Version:</B>n" + productVersion +
"</UL>");
48
Using MetaData: Example
(Continued)(Continued)
out.println("<TABLE BORDER='1'>");
// Discover and print headings// Discover and print headings
ResultSetMetaData resultSetMetaData =
resultSet.getMetaData();
int columnCount = resultSetMetaData.getColumnCount();
out.println("<TR>");
// Column index starts at 1 (a la SQL), not 0 (a la Java).
for(int i=1; i <= columnCount; i++) {
out.printf("<TH>%s", resultSetMetaData.getColumnName(i));
}
out.println();
}}
}
49
Using MetaData: Results
50
Ā© 2010 Marty Hall
Using PreparedUsing Prepared
Statements
(Parameterized Commands)
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Overview
ā€¢ Situation
ā€“ You are repeatedly executing query or update where
format stays consistent, but values change
ā€“ You can make a parameterized query or update then passā€“ You can make a parameterized query or update, then pass
in values for the placeholders
ā€¢ Advantagesg
ā€“ More convenient than string concatenation
ā€“ Significantly faster with most drivers and databases
If h l i d h l iblā€“ If the values contain user data, much less susceptible to
SQL injection attacks
52
Steps
ā€¢ Make a placeholder
A T bl h l (i d S i )ā€“ Assume someTable has two columns (int and String)
String template =
"INSERT INTO someTable VALUES(?, ?)";
P dSt t t i tPreparedStatement inserter =
connection.prepareStatement(template);
ā€¢ Substitute in values
ā€“ Use setInt(index), setString(index), etc. Remember
indices start with 1, not 0.
for(ā€¦) {o ( ) {
inserter.setInt(1, someInt);
inserter.setString(2, someString)
}}
ā€¢ Execute command
ā€¢ inserter.executeUpdate();
53
Creating the Database
ā€¢ Roles
ā€“ Most JDBC developers do not need to create the database
ā€“ That is the job of the database system admin
Apache Derbyā€¢ Apache Derby
ā€“ You can run Derby-specific scripts and create the
database interactivelyy
ā€“ Or, you can use Java and JDBC
ā€¢ Using PreparedStatement simplifies the process
Si l ā€œ D t b ā€ lā€¢ Simple ā€œmyDatabaseā€ example
ā€“ Created with Java and JDBC
Triggered from a ServletContextListener so databaseā€“ Triggered from a ServletContextListener so database
creation code is executed at least once
54
Creating Sample Database
public class EmbeddedDbCreator {
// Driver class not needed in JDBC 4 0 (Java SE 6)// Driver class not needed in JDBC 4.0 (Java SE 6)
// private String driver =
// "org.apache.derby.jdbc.EmbeddedDriver";
private String protocol = "jdbc:derby:";p g p j y
private String username = "someuser";
private String password = "somepassword";
private String dbName = "myDatabase";
private String tableName = "employees";
private Properties userInfo;
bli E b dd dDbC t () {public EmbeddedDbCreator() {
userInfo = new Properties();
userInfo.put("user", username);
userInfo put("password" password);userInfo.put( password , password);
}
55
Creating Sample Database
(Continued)(Continued)
public void createDatabase() {
Employee[] employees = {Employee[] employees {
new Employee(1, "Larry", "Ellison", "CEO",
1234567890),
new Employee(2, "Charles", "Phillips", "President",p y ( , , p , ,
23456789),
new Employee(3, "Safra", "Catz", "President",
32654987),
ā€¦
};
56
Creating Sample Database
(Continued)(Continued)
try {
String dbUrl = protocol + dbName + ";create=true";String dbUrl protocol + dbName + ;create true ;
Connection connection =
DriverManager.getConnection(dbUrl, userInfo);
Statement statement = connection.createStatement();
String format = "VARCHAR(20)";
String tableDescription =
String.format
("CREATE TABLE %s" +( CREATE TABLE %s +
"(id INT, firstname %s, lastname %s, " +
"position %s, salary INT)",
tableName, format, format, format);
statement.execute(tableDescription);
57
Creating Sample Database
(Continued)(Continued)
String template =
String.format("INSERT INTO %s VALUES(?, ?, ?, ?, ?)",String.format( INSERT INTO %s VALUES(?, ?, ?, ?, ?) ,
tableName);
PreparedStatement inserter =
connection.prepareStatement(template);
for(Employee e: employees) {
inserter.setInt(1, e.getEmployeeID());
inserter.setString(2, e.getFirstName());
inserter setString(3 e getLastName());inserter.setString(3, e.getLastName());
inserter.setString(4, e.getPosition());
inserter.setInt(5, e.getSalary());
inserter.executeUpdate();
System.out.printf("Inserted %s %s.%n",
e.getFirstName(),
e.getLastName());
}}
inserter.close();
connection.close();
58
Triggering Database Creation
ā€¢ Database needs to be created once
ā€“ Not for every request
ā€“ Not even for every time server restarts
Goalā€¢ Goal
ā€“ Create table when Web app is loaded
ā€¢ try/catch block in creation code halts process if tabletry/catch block in creation code halts process if table
already exists
ā€¢ Possible approaches
S l i h i d i i i d b l i hā€“ Servlet with creation code in init, and web.xml with
<load-on-startup>1</load-on-startup>
ā€“ ServletContextListenerServletContextListener
ā€¢ Same effect as above, but more straightforward
ā€“ For desktop apps, just manually run the code once.59
Triggering Database Creation:
ListenerListener
package coreservlets;
import javax.servlet.*;
public class DatabaseInitializer
implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
new EmbeddedDbCreator().createDatabase();
}}
public void contextDestroyed(ServletContextEvent event) {}
}
60
Triggering Database Creation:
web xmlweb.xml
ā€¦
<listener><listener>
<listener-class>
coreservlets.DatabaseInitializer
</listener-class>
</listener>
61
Ā© 2010 Marty Hall
Advanced Features
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Transactions
ā€¢ Idea
ā€“ By default, after each SQL statement is executed the
changes are automatically committed to the database
ā€“ Turn auto-commit off to group two or more statementsā€“ Turn auto-commit off to group two or more statements
together into a transaction
ti tA t C it(f l )connection.setAutoCommit(false);
ā€“ Call commit to permanently record the changes to the
database after executing a group of statements
ā€“ Call rollback if an error occurs
63
Transactions: Example
Connection connection =
DriverManager.getConnection(url, userProperties);g g ( , p );
connection.setAutoCommit(false);
try {
statement.executeUpdate(...);
statement executeUpdate( );statement.executeUpdate(...);
...
connection.commit();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException sqle) {
// report problem// report problem
}
} finally {
try {
ti l ()connection.close();
} catch (SQLException sqle) { }
}
64
Useful Connection Methods
(for Transactions)(for Transactions)
ā€¢ getAutoCommit/setAutoCommit
ā€“ By default, a connection is set to auto-commit
ā€“ Retrieves or sets the auto-commit mode
commitā€¢ commit
ā€“ Force all changes since the last call to commit to become
permanentp
ā€“ Any database locks currently held by this Connection
object are released
llb kā€¢ rollback
ā€“ Drops all changes since the previous call to commit
Releases any database locks held by this Connectionā€“ Releases any database locks held by this Connection
object
65
Using JNDI and DataSource
ā€¢ Idea
ā€“ Use abstract name to get connection from a data source
ā€¢ Advantages
L h d i h h i dā€“ Lets you change data source without changing code
ā€“ Available in multiple Web apps for network databases
(not embedded Derby!)( y )
ā€¢ Disadvantage
ā€“ Requires server-specific registration of data source
ā€¢ Code for steps 1-3 replaced by:
Context context = new InitialContext();
DataSource dataSource = (DataSource)context lookupDataSource dataSource = (DataSource)context.lookup
("java:comp/env/jdbc/dbName");
Connection connection = dataSource.getConnection();
66
DataSource: Tomcat Configuration
(META-INF/context xml)(META-INF/context.xml)
<?xml version="1.0" encoding="UTF-8"?>
<Context><Context>
<Resource
name="jdbc/myDatabase"
driverClassName="org apache derby jdbc ClientDriver"driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby:myDatabase"
type="javax.sql.DataSource"
" "username="someuser"
password="somepassword"
auth="Container"
A ti "8" /maxActive="8" />
</Context>
67
More JDBC Options
ā€¢ Stored procedures
ā€¢ Changing buffer size
ā€¢ Connection poolingp g
ā€¢ Hibernate/JPA and other ORM tools
ā€“ See tutorials at coreservlets.com
ā€¢ JSP Standard Tag Library (JSTL)
ā€“ Custom tags to hide JDBC details.g
ā€¢ Some developers use JSTL to loop down the ResultSet.
Disadvantage: ties presentation layer to JDBC.
ā€¢ Some developers use JSTL to actually do queries Simpleā€¢ Some developers use JSTL to actually do queries. Simple.
Disadvantage: very inflexible and violates MVC principle.
68
Ā© 2010 Marty Hall
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
JDBC and Derby References
ā€¢ Books
JDBC API T i l d R f b M d Fi hā€“ JDBC API Tutorial and Reference by Maydene Fisher,
Jon Ellis, and Jonathan Bruce (Prentice Hall)
ā€“ Expert Oracle JDBC Programming by R.M. Menon
(APress)
ā€“ JDBC Recipes: A Problem-Solution Approach by
Mahmoud Parsian (APress)( )
ā€¢ Sun JDBC tutorial
ā€“ http://java.sun.com/docs/books/tutorial/jdbc/
Derb referencesā€¢ Derby references
ā€“ Derby beginnerā€™s tutorial
ā€¢ http://db.apache.org/derby/papers/DerbyTut/g y y
ā€“ Derby 10.4 manuals
ā€¢ http://db.apache.org/derby/manuals/index.html#docs_10.4
70
Summary
1. Load the driver
N t i d i J 6 Cl f N th iā€“ Not required in Java 6; use Class.forName otherwise
2. Define the Connection URL
ā€“ jdbc:vendor:blah (vendor gives exact format)
3. Establish the Connection
ā€“ DriverManager.getConnection
4 Create a Statement object4. Create a Statement object
ā€“ connection.createStatement
5. Execute a query
ā€“ statement.executeQuery
6. Process the results
ā€“ Loop using resultSet.next()Loop using resultSet.next()
ā€“ Call getString, getInt, etc.
7. Close the connection
71
Ā© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

More Related Content

What's hot

JSR-222 Java Architecture for XML Binding
JSR-222 Java Architecture for XML BindingJSR-222 Java Architecture for XML Binding
JSR-222 Java Architecture for XML BindingHeiko Scherrer
Ā 
Hibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examplesHibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examplesEr. Gaurav Kumar
Ā 
Best Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBBest Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBMartin Grebac
Ā 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5Smita B Kumar
Ā 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final) Hitesh-Java
Ā 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2Hitesh-Java
Ā 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
Ā 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationKhoa Nguyen
Ā 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
Ā 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
Ā 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connectionWaheed Warraich
Ā 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernateelliando dias
Ā 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOPHitesh-Java
Ā 
Understanding
Understanding Understanding
Understanding Arun Gupta
Ā 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
Ā 

What's hot (18)

Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
Ā 
JSR-222 Java Architecture for XML Binding
JSR-222 Java Architecture for XML BindingJSR-222 Java Architecture for XML Binding
JSR-222 Java Architecture for XML Binding
Ā 
Hibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examplesHibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examples
Ā 
Best Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXBBest Practices for Interoperable XML Databinding with JAXB
Best Practices for Interoperable XML Databinding with JAXB
Ā 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
Ā 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
Ā 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
Ā 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
Ā 
Jaxb
JaxbJaxb
Jaxb
Ā 
Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
Ā 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
Ā 
13 java beans
13 java beans13 java beans
13 java beans
Ā 
JAXB
JAXBJAXB
JAXB
Ā 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
Ā 
JPA and Hibernate
JPA and HibernateJPA and Hibernate
JPA and Hibernate
Ā 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
Ā 
Understanding
Understanding Understanding
Understanding
Ā 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
Ā 

Viewers also liked

02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
Ā 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
Ā 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPsKind of Digital
Ā 
07 cookies
07 cookies07 cookies
07 cookiessnopteck
Ā 
11 page-directive
11 page-directive11 page-directive
11 page-directivesnopteck
Ā 
04 request-headers
04 request-headers04 request-headers
04 request-headerssnopteck
Ā 

Viewers also liked (6)

02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
Ā 
03 form-data
03 form-data03 form-data
03 form-data
Ā 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPs
Ā 
07 cookies
07 cookies07 cookies
07 cookies
Ā 
11 page-directive
11 page-directive11 page-directive
11 page-directive
Ā 
04 request-headers
04 request-headers04 request-headers
04 request-headers
Ā 

Similar to 10 jdbc

14 mvc
14 mvc14 mvc
14 mvcsnopteck
Ā 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part ISivaSankari36
Ā 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentationnrjoshiee
Ā 
15 expression-language
15 expression-language15 expression-language
15 expression-languagesnopteck
Ā 
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004derek_clark_ashmore
Ā 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Ramamohan Chokkam
Ā 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3IMC Institute
Ā 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedIMC Institute
Ā 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
Ā 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
Ā 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
Ā 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivityarikazukito
Ā 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming TechniquesRaji Ghawi
Ā 

Similar to 10 jdbc (20)

14 mvc
14 mvc14 mvc
14 mvc
Ā 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
Ā 
Jdbc presentation
Jdbc presentationJdbc presentation
Jdbc presentation
Ā 
15 expression-language
15 expression-language15 expression-language
15 expression-language
Ā 
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Jdbc Best Practices - DB2/ IDUG - Orlando, May 10, 2004
Ā 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
Ā 
Jdbc
JdbcJdbc
Jdbc
Ā 
Jdbc
JdbcJdbc
Jdbc
Ā 
Json generation
Json generationJson generation
Json generation
Ā 
Jsp
JspJsp
Jsp
Ā 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
Ā 
Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3Java Web Programming Using Cloud Platform: Module 3
Java Web Programming Using Cloud Platform: Module 3
Ā 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
Ā 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
Ā 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Ā 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Ā 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
Ā 
10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
Ā 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Ā 
Jdbc
JdbcJdbc
Jdbc
Ā 

More from snopteck

10 jdbc
10 jdbc10 jdbc
10 jdbcsnopteck
Ā 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
Ā 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
Ā 
06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
Ā 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
Ā 
01 web-apps
01 web-apps01 web-apps
01 web-appssnopteck
Ā 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setupsnopteck
Ā 

More from snopteck (7)

10 jdbc
10 jdbc10 jdbc
10 jdbc
Ā 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
Ā 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
Ā 
06 response-headers
06 response-headers06 response-headers
06 response-headers
Ā 
05 status-codes
05 status-codes05 status-codes
05 status-codes
Ā 
01 web-apps
01 web-apps01 web-apps
01 web-apps
Ā 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
Ā 

Recently uploaded

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
Ā 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
Ā 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
Ā 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
Ā 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
Ā 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
Ā 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
Ā 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
Ā 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
Ā 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
Ā 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
Ā 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
Ā 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
Ā 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
Ā 
Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Nellā€™iperspazio con Rocket: il Framework Web di Rust!Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Nellā€™iperspazio con Rocket: il Framework Web di Rust!Commit University
Ā 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
Ā 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo GarcĆ­a Lavilla
Ā 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
Ā 

Recently uploaded (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
Ā 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
Ā 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
Ā 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
Ā 
Hot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort Service
Hot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort ServiceHot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort Service
Hot Sexy call girls in Panjabi Bagh šŸ” 9953056974 šŸ” Delhi escort Service
Ā 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
Ā 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
Ā 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Ā 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
Ā 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
Ā 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
Ā 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
Ā 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
Ā 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
Ā 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
Ā 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
Ā 
Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Nellā€™iperspazio con Rocket: il Framework Web di Rust!Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Nellā€™iperspazio con Rocket: il Framework Web di Rust!
Ā 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
Ā 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
Ā 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
Ā 

10 jdbc

  • 1. Ā© 2010 Marty Hall Database Access with JDBCOriginals of Slides and Source Code for Examples:Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/msajsp.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Ā© 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/.at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Contact hall@coreservlets.com for details.
  • 2. Overview ā€¢ Overview of JDBC technology ā€¢ JDBC design strategies ā€¢ Using Apache Derby (Java DB) ā€¢ Seven basic steps in using JDBC ā€¢ Using JDBC from desktop Java apps ā€¢ Using JDBC from Web apps ā€¢ Prepared statements (parameterized d )commands) ā€¢ Meta data Transaction controlā€¢ Transaction control 5 Ā© 2010 Marty Hall Overview Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 3. JDBC Introduction ā€¢ JDBC provides a standard library for i l i l d baccessing relational databases ā€“ API standardizes ā€¢ Way to establish connection to databaseā€¢ Way to establish connection to database ā€¢ Approach to initiating queries ā€¢ Method to create stored (parameterized) queries Th d t t t f lt (t bl )ā€¢ The data structure of query result (table) ā€“ Determining the number of columns ā€“ Looking up metadata, etc. ā€“ API does not standardize SQL syntax ā€¢ JDBC is not embedded SQL ā€“ JDBC classes are in the java.sql packageJDBC classes are in the java.sql package ā€¢ Note: JDBC is not officially an acronym; ā€“ Unofficially, ā€œJava DataBase Connectivityā€ is commonly used7 On-line Resources ā€¢ Sunā€™s JDBC Site ā€“ http://java.sun.com/javase/6/docs/technotes/guides/jdbc/ ā€¢ JDBC Tutorial h //j /d /b k / i l/jdb /ā€“ http://java.sun.com/docs/books/tutorial/jdbc/ ā€¢ API for java.sql http://java sun com/javase/6/docs/api/java/sql/ā€“ http://java.sun.com/javase/6/docs/api/java/sql/ package-summary.html ā€¢ List of Available JDBC Drivers ā€“ http://developers.sun.com/product/jdbc/drivers ā€¢ Or, just look in your database vendorā€™s documentation 8
  • 4. JDBC Drivers ā€¢ JDBC consists of two parts: ā€“ JDBC API, a purely Java-based API ā€“ JDBC Driver Manager which Java Application JDBC API ā€“ JDBC Driver Manager,which communicates with vendor-specific drivers that f th l i ti JDBC Driver Manager JDBC Driver API perform the real communication with the database. ā€¢ Point: translation to vendor Vendor Specific JDBC Driver JDBC-ODBC Bridge format is performed on the client ā€“ No changes needed t Vendor Specific ODBC Driver Database to server ā€“ Driver (translator) needed on client 9 Database JDBC Data Types JDBC Type Java TypeJDBC Type Java Type BIT boolean TINYINT byte SMALLINT short INTEGER intINTEGER int BIGINT long REAL float FLOAT double DOUBLE JDBC Type Java Type NUMERIC BigDecimal DECIMAL DATE java sql DateDOUBLE BINARY byte[] VARBINARY LONGVARBINARY CHAR String DATE java.sql.Date TIME java.sql.Timestamp TIMESTAMP CLOB Clob BLOB Blob VARCHAR LONGVARCHAR BLOB Blob ARRAY Array DISTINCT mapping of underlying type STRUCT Struct REF Ref 10 REF Ref JAVA_OBJECT underlying Java class
  • 5. Ā© 2010 Marty Hall Steps for Using JDBC Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. JDBC Design Strategies ā€¢ In general, plan for changes to data access ā€“ Limit the data access to single area of code ā€¢ Donā€™t distribute JDBC calls throughout the code ā€¢ Plan ahead for changing from JDBC to Hibernate orPlan ahead for changing from JDBC to Hibernate or another tool ā€“ Donā€™t return JDBC-specific (or Hibernate-specific) objects from the data access layerobjects from the data-access layer ā€¢ Return ordinary Java objects instead ā€¢ In JDBC, plan for changes, p g ā€“ Limit the definition of driver, URL, etc. to single location ā€¢ Let database experts do their stuff ā€“ If database is complex, let database expert design the database and design the queries 12
  • 6. Seven Basic Steps in Using JDBCUsing JDBC 1. Load the driver ā€“ Not required in Java 6, so Java 6 needs only 6 steps. 2. Define the Connection URL 3 E t bli h th C ti3. Establish the Connection 4. Create a Statement object 5 E t5. Execute a query 6. Process the results 7 Cl th ti7. Close the connection 13 JDBC Step 1: Load the Driver ā€¢ Not required in Java 6 ā€“ In Java SE 6.0 and later (JDBC 4.0 and later), the driver is loaded automatically. ā€¢ Java 5 and earlierā€¢ Java 5 and earlier ā€“ Load the driver class only. The class has a static initialization block that makes an instance and registers itg with the DriverManager. try { Class.forName("com.mysql.jdbc.Driver"); Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException cnfe) { System.out.println("Error loading driver: " cnfe); } 14
  • 7. JDBC Step 2: Define the Connection URLConnection URL ā€¢ Remote databases F t i ā€œjdb d N ā€ā€“ Format is ā€œjdbc:vendorName:ā€¦ā€ ā€¢ Address contains hostname, port, and database name ā€¢ Exact details given by supplier of JDBC driver ā€¢ Embedded Derby databaseā€¢ Embedded Derby database ā€“ The ā€œJava DBā€ (i.e., Apache Derby) is bundled with Java 6 and can be used for a database embedded in the same Java VM that runs the app serverthat runs the app server. ā€“ Format is ā€œjdbc:derby:databaseNameā€ ā€¢ Examples String host = "dbhost.yourcompany.com"; String dbName = "someName"; int port = 1234; String mySqlUrl = "jdbc:mysql//" + host + ":" + port +g y q j y q p "/" + dbName; String embeddedDerbyUrl = "jdbc:derby" + dbName; 15 JDBC Step 3: Establish the ConnectionConnection ā€¢ Get the main connection Properties userInfo = new Properties(); userInfo.put("user", "jay_debesee"); userInfo.put("password", "secret"); Connection connection = DriverManager.getConnection(mySqlUrl, userInfo); ā€¢ Optionally, look up info about the databasep y, p DatabaseMetaData dbMetaData = connection.getMetaData(); String productName =g p dbMetaData.getDatabaseProductName(); System.out.println("Database: " + productName); String productVersion =g p dbMetaData.getDatabaseProductVersion(); System.out.println("Version: " + productVersion); 16
  • 8. JDBC Step 4: Make a Statement ā€¢ Idea ā€“ A Statement is used to send queries or commands ā€¢ Statement types S P dS C ll bl Sā€“ Statement, PreparedStatement, CallableStatement ā€¢ Details on other types given later ā€¢ ExampleExample Statement statement = connection.createStatement(); 17 JDBC Step 5: Execute a Query ā€¢ Idea ā€“ statement.executeQuery("SELECT ā€¦ FROM ā€¦"); ā€¢ This version returns a ResultSet ā€“ statement executeUpdate("UPDATE ");ā€“ statement.executeUpdate( UPDATE ā€¦ ); ā€“ statement.executeUpdate("INSERT ā€¦"); ā€“ statement.executeUpdate("DELETEā€¦"); ā€“ statement.execute("CREATE TABLEā€¦"); ā€“ statement.execute("DROP TABLE ā€¦"); E lā€¢ Example String query = "SELECT col1, col2, col3 FROM sometable"; ResultSet resultSet = statement.executeQuery(query); 18
  • 9. JDBC Step 6: Process the ResultResult ā€¢ Important ResultSet methods ā€“ resultSet.next() ā€¢ Goes to the next row. Returns false if no next row. ā€“ resultSet getString("columnName")ā€“ resultSet.getString( columnName ) ā€¢ Returns value of column with designated name in current row, as a String. Also getInt, getDouble, getBlob, etc. ltS t tSt i ( l I d )ā€“ resultSet.getString(columnIndex) ā€¢ Returns value of designated column. First index is 1 (ala SQL), not 0 (ala Java). ā€“ resultSet.beforeFirst() ā€¢ Moves cursor before first row, as it was initially. Also first ā€“ resultSet absolute(rowNum)resultSet.absolute(rowNum) ā€¢ Moves cursor to given row (starting with 1). Also last and afterLast. 19 JDBC Step 6: Process the ResultResult ā€¢ Assumption ā€“ Query was ā€œSELECT first, last, address FROMā€¦ā€ ā€¢ Using column names while(resultSet next()) {while(resultSet.next()) { System.out.printf( "First name: %s, last name: %s, address: %s%n", resultSet.getString("first"), resultSet.getString("last"), resultSet.getString("address")); } U i l i diā€¢ Using column indices while(resultSet.next()) { System.out.printf( "First name: %s last name: %s address: %s%n""First name: %s, last name: %s, address: %s%n", resultSet.getString(1), resultSet.getString(2), resultSet.getString(3)); }20
  • 10. JDBC Step 7: Close the ConnectionConnection ā€¢ Idea ā€“ When totally done, close the database connection. However, opening a new connection is typically much more expensive than sending queries on existingmore expensive than sending queries on existing connections, so postpone this step as long as possible. ā€“ Many JDBC drivers do automatic connection pooling h l li i i l ili iā€“ There are also many explicit connection pool utilities ā€¢ Example connection close();connection.close(); 21 Ā© 2010 Marty Hall Using Apache Derby Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 11. Apache Derby: Overview ā€¢ Overview ā€“ Written in Java. Good for small/medium applications (less than gigabyte database size, few queries/second) ā€“ Bundled with Java 6 but latest version can beā€“ Bundled with Java 6, but latest version can be downloaded from Apache for Java 1.4 and later. ā€¢ Embedded mode ā€“ Database runs in same VM as Java app. Does not accept network connections. Perfect for Web appsā€“ Perfect for Web apps ā€¢ Incredibly easy to set up. Just drop in one JAR file ā€¢ Good if database is accessed only from the Web apps ā€¢ Standalone mode ā€“ Runs in separate VM. Accepts network connections.23 Downloading and Installing DerbyDerby ā€¢ Downloading and documentation http://db apache org/derby/ā€“ http://db.apache.org/derby/ ā€¢ Use in embedded mode ā€“ Code F W b d d b j i WEB INF/libā€¢ For Web apps, drop derby.jar in WEB-INF/lib ā€¢ For other apps, put derby.jar in CLASSPATH ā€“ URL ā€¢ jdbc:derby:databaseNamejdbc:derby:databaseName ā€“ Driver class name ā€¢ org.apache.derby.jdbc.EmbeddedDriver ā€¢ Not needed in Java 6! ā€“ Username/password ā€¢ Any are legal since DB runs inside the application. ā€¢ Use in standalone mode ā€“ See http://db.apache.org/derby/papers/DerbyTut/ ā€“ Consider MySQL, Oracle, etc. as alternatives 24
  • 12. Setup Summary ā€¢ Setup summary l d d l b f db h /d b /ā€“ Downloaded latest Derby ZIP from db.apache.org/derby/ ā€¢ db-derby-10.5.3.0-bin.zip, but any recent version is fine ā€¢ You can also use version bundled with JDK 1.6.x ā€“ Unzipped ā€“ Put install_dir/lib/derby.jar into CLASSPATH ā€¢ Many options in Eclipse but if you make a Dynamic Webā€¢ Many options in Eclipse, but if you make a Dynamic Web Project, drop derby.jar in WebContent/WEB-INF/lib ā€“ Thatā€™s it (for embedded usage)! C thi 90 d t i t lli O lā€¢ Compare this 90 second process to installing Oracle ā€¢ Creating database ā€“ Can be created directly from Java using SQL commandsCan be created directly from Java using SQL commands via JDBC. See later slides. Need to run creator code at least once before accessing database. 25 Setup Details: Desktop Apps ā€¢ Putting derby.jar in CLASSPATHCLASSPATH ā€“ R-click on project in Eclipse, create new folder called ā€œlibā€. Put derby.jar in libin lib. ā€“ R-click on project. Properties ļƒ  Java Build Path ļƒ  Libraries ļƒ  Add JARs N i t t j t/lib/ d l tā€“ Navigate to project/lib/ and select derby.jar. Press OK. ā€¢ Creating database ā€“ Manually run database creation code. See ā€œPrepared Statementsā€ section for code, but this needs to be done once l I t l h tonly. In most real apps, you have to query database, but someone else creates the database.26
  • 13. Setup Details: Web Apps ā€¢ Putting derby.jar in CLASSPATH ā€“ Copy derby.jar to WEB-INF/lib ā€¢ Creating database R d b i d S ā€œP d S ā€ā€“ Run database creation code. See ā€œPrepared Statementsā€ section for code . This needs to be done once only, so best way is to do it automatically in ServletContextListener. Iny y most real apps, you have to query database, but someone else creates the database. ā€¢ Reminder: full code can be downloaded fromReminder: full code can be downloaded from http://courses.coreservlets.com/Course-Materials/ msajsp.html, so you can get db creation code there. 27 Ā© 2010 Marty Hall Using JDBC fromUsing JDBC from Desktop Javap Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 14. Approach ā€¢ Same basic steps ā€“ Load the driver ā€“ Define the Connection URL ā€“ Establish the ConnectionEstablish the Connection ā€“ Create a Statement object ā€“ Execute a query ā€“ Process the results ā€“ Close the connection ā€¢ Differences from JDBC in Web appsā€¢ Differences from JDBC in Web apps ā€“ Results are often put into Swing or AWT interfaces ā€“ If you use value in calculation, use getInt, getDouble, etc.y , g , g , ā€“ If value is only used for display in GUI, you can use getString even if value is another type 29 Sample Database ā€¢ Table name ā€“ employees ā€¢ Column names id (int) The employee IDā€“ id (int). The employee ID. ā€“ firstname (varchar/String). Employeeā€™s given name. ā€“ lastname (varchar/String). Employeeā€™s family name. ā€“ position (varchar/String). Corporate position (eg, ā€œceoā€). ā€“ salary (int). Yearly base salary. ā€¢ Database nameā€¢ Database name ā€“ myDatabase ā€¢ Note ā€“ See ā€œPrepared Statementsā€ section for code that created DB 30
  • 15. Example: Printing Employee InfoPrinting Employee Info package coreservlets; The URL and the driver are the only parts that are specific to Derby. So, if you switch to MySql, Oracle, etc., you have to change those two lines (or just one line in Java 6 with JDBC 4 driver, since the driver no longer needs to be declared in that situation). The rest of the code is import java.sql.*; import java.util.*; database independent. public class ShowEmployees { public static void main(String[] args) { St i l "jdb d b D t b "String url = "jdbc:derby:myDatabase"; Properties userInfo = new Properties(); userInfo.put("user", "someuser"); ( )userInfo.put("password", "somepassword"); String driver = "org.apache.derby.jdbc.EmbeddedDriver"; showSalaries(url, userInfo, driver); } 31 Example: Printing Employee Info (Connecting to Database)Info (Connecting to Database) public static void showSalaries(String url, Properties userInfo,Properties userInfo, String driverClass) { try { // Load the driver. NOT NEEDED in Java 6! // Class.forName(driverClass); // Establish network connection to database. Connection connection =Connection connection = DriverManager.getConnection(url, userInfo); System.out.println("Employeesn=========="); // Create a statement for executing queries. Statement statement = connection.createStatement(); String query = "SELECT * FROM employees ORDER BY salary"; // S d t d t b d t lt// Send query to database and store results. ResultSet resultSet = statement.executeQuery(query); 32
  • 16. Example: Printing Employee Info (Processing Results)Info (Processing Results) while(resultSet.next()) { int id = resultSet.getInt("id");int id resultSet.getInt( id ); String firstName = resultSet.getString("firstname"); String lastName = resultSet.getString("lastname"); String position = resultSet.getString("position"); int salary = resultSet.getInt("salary"); System.out.printf ("%s %s (%s, id=%s) earns $%,d per year.%n", firstName lastName position id salary);firstName, lastName, position, id, salary); } connection.close(); } catch(Exception e) { System.err.println("Error with connection: " + e); } 33 Example: Printing Employee Info (Output)Info (Output) Employees ========== Gary Grunt (Gofer, id=12) earns $7,777 per year. Gabby Grunt (Gofer, id=13) earns $8,888 per year. Cathy Coder (Peon, id=11) earns $18,944 per year. Cody Coder (Peon, id=10) earns $19,842 per year. Danielle Developer (Peon, id=9) earns $21,333 per year. David Developer (Peon, id=8) earns $21,555 per year. Joe Hacker (Peon, id=6) earns $23,456 per year. Jane Hacker (Peon, id=7) earns $32,654 per year. Keith Block (VP, id=4) earns $1,234,567 per year. Thomas Kurian (VP id=5) earns $2 431 765 per yearThomas Kurian (VP, id=5) earns $2,431,765 per year. Charles Phillips (President, id=2) earns $23,456,789 per year. Safra Catz (President, id=3) earns $32,654,987 per year. Larry Ellison (CEO, id=1) earns $1,234,567,890 per year.y ( , ) $ , , , p y 34
  • 17. Ā© 2010 Marty Hall Using JDBC fromUsing JDBC from Web Appspp Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Approach ā€¢ Same basic steps L d h d iā€“ Load the driver ā€“ Define the Connection URL ā€“ Establish the Connection ā€“ Create a Statement object ā€“ Execute a query Process the resultsā€“ Process the results ā€“ Close the connection ā€¢ Differences from JDBC in desktop appsp pp ā€“ Results are often put into HTML ā€“ If value is inserted directly into HTML, you can use getString even if value is another typegetString even if value is another type ā€“ To support concurrent access, you usually use a driver that supports connection pooling 36
  • 18. Sample Database ā€¢ Table name ā€“ employees ā€¢ Column names id (int) The employee IDā€“ id (int). The employee ID. ā€“ firstname (varchar/String). Employeeā€™s given name. ā€“ lastname (varchar/String). Employeeā€™s family name. ā€“ position (varchar/String). Corporate position (eg, ā€œceoā€). ā€“ salary (int). Yearly base salary. ā€¢ Database nameā€¢ Database name ā€“ myDatabase ā€¢ Note ā€“ See ā€œPrepared Statementsā€ section for code that created DB 37 A Servlet to Show Employee InfoInfo ā€¢ Overview ā€“ Same sample database as before ā€¢ DB type: Derby in embedded mode ā€¢ DB name: employeesDB name: employees ā€¢ Columns: id, firstname, lastname, position, salary ā€¢ Goal ā€“ Build HTML table that shows all employees ā€¢ Approach B ild HTML t bl di tl i l tā€“ Build HTML table directly in servlet ā€¢ MVC combined with JSTL or custom tags might work better, but this lecture does not assume familiarity with th t ithose topics ā€¢ Basic JDBC code is the same either way 38
  • 19. Employee Info Servlet public class EmployeeServlet1 extends HttpServlet { //private final String driver//private final String driver = // "org.apache.derby.jdbc.EmbeddedDriver"; protected final String url = "jdbc:derby:myDatabase"; protected final String tableName = "employees"; protected final String username = "someuser"; protected final String password = "somepassword"; The URL and the driver are the only parts that are specific to Derby. So, if you switch to MySql, Oracle, etc., you have to change those two lines (or just one line in Java 6 with JDBC 4 driver, 39 Oracle, etc., you have to change those two lines (or just one line in Java 6 with JDBC 4 driver, since the driver no longer needs to be declared in that situation). The rest of the code is database independent. Employee Info Servlet (Continued)(Continued) public void doGet(HttpServletRequest request, HttpServletResponse response)p p p ) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " + "Transitional//EN"n"; String title = "Company Employees";St g t t e Co pa y p oyees ; out.print(docType + "<HTML>n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>n" + / / "<LINK REL='STYLESHEET' HREF='./css/styles.css'n" + " TYPE='text/css'>" + "<BODY><CENTER>n" + "<TABLE CLASS='TITLE' BORDER='5'>" +<TABLE CLASS TITLE BORDER 5 > + " <TR><TH>" + title + "</TABLE><P>"); showTable(out); out.println("</CENTER></BODY></HTML>"); }40
  • 20. Employee Info Servlet (Continued)(Continued) protected void showTable(PrintWriter out) { try {try { Connection connection = getConnection(); Statement statement = connection.createStatement(); String query = "SELECT * FROM " + tableName;String query = "SELECT * FROM " + tableName; ResultSet resultSet = statement.executeQuery(query); printTableTop(connection, resultSet, out); i tT bl B d ( ltS t t)printTableBody(resultSet, out); connection.close(); } catch(Exception e) { S t i tl ("E " )System.err.println("Error: " + e); } } 41 Employee Info Servlet (Continued)(Continued) protected Connection getConnection() throws Exception {throws Exception { // Load database driver if it's not already loaded. // Not needed in JDBC 4 (Java SE 6). Uncomment // for earlier versions// for earlier versions. // Class.forName(driver); // E t bli h t k ti t d t b// Establish network connection to database. Properties userInfo = new Properties(); userInfo.put("user", username); I f t(" d" d)userInfo.put("password", password); Connection connection = DriverManager.getConnection(url, userInfo); return(connection); } 42
  • 21. Employee Info Servlet (Continued)(Continued) protected void printTableTop(Connection connection, ResultSet resultSetResultSet resultSet, PrintWriter out) throws SQLException { out.println("<TABLE BORDER='1'>");out.println( <TABLE BORDER 1 > ); // Print headings from explicit heading names String[] headingNames = { "ID", "First Name", "Last Name",{ , , , "Position", "Salary" }; out.print("<TR>"); for (String headingName : headingNames) {g g g out.printf("<TH>%s", headingName); } out.println(); } 43 Employee Info Servlet (Continued)(Continued) protected void printTableBody(ResultSet resultSet, PrintWriter out)PrintWriter out) throws SQLException { // Step through each row in the result set and print cells while(resultSet.next()) { out.println("<TR ALIGN='RIGHT'>"); out.printf(" <TD>%d", resultSet.getInt("id")); out.printf(" <TD>%s", resultSet.getString("firstname")); out.printf(" <TD>%s", resultSet.getString("lastname")); out.printf(" <TD>%s", resultSet.getString("position")); out.printf(" <TD>$%,d%n", resultSet.getInt("salary")); }} out.println("</TABLE>"); } }} 44
  • 22. Employee Info Servlet (Results) 45 Ā© 2010 Marty Hall Using MetaData Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 23. Using MetaData ā€¢ Idea ā€“ For most queries, you know column names and database version ahead of time. But you can discover this dynamically as well.dynamically as well. ā€¢ System-wide data ā€“ connection.getMetaData().getDatabaseProductName()g () g () ā€“ connection.getMetaData().getDatabaseProductVersion() ā€¢ Table-specific data ā€“ resultSet.getMetaData().getColumnCount() ā€¢ When using the result, remember that the index starts at 1, not 0 ā€“ resultSet.getMetaData().getColumnName() 47 Using MetaData: Example public class EmployeeServlet2 extends EmployeeServlet1 { protected void printTableTop(Connection connectionprotected void printTableTop(Connection connection, ResultSet resultSet, PrintWriter out) throws SQLException {throws SQLException { // Look up info about the database as a whole. DatabaseMetaData dbMetaData = connection.getMetaData(); String productName =g p dbMetaData.getDatabaseProductName(); String productVersion = dbMetaData.getDatabaseProductVersion();g out.println("<UL>n" + " <LI><B>Database:</B>n" + productName + " <LI><B>Version:</B>n" + productVersion + "</UL>"); 48
  • 24. Using MetaData: Example (Continued)(Continued) out.println("<TABLE BORDER='1'>"); // Discover and print headings// Discover and print headings ResultSetMetaData resultSetMetaData = resultSet.getMetaData(); int columnCount = resultSetMetaData.getColumnCount(); out.println("<TR>"); // Column index starts at 1 (a la SQL), not 0 (a la Java). for(int i=1; i <= columnCount; i++) { out.printf("<TH>%s", resultSetMetaData.getColumnName(i)); } out.println(); }} } 49 Using MetaData: Results 50
  • 25. Ā© 2010 Marty Hall Using PreparedUsing Prepared Statements (Parameterized Commands) Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Overview ā€¢ Situation ā€“ You are repeatedly executing query or update where format stays consistent, but values change ā€“ You can make a parameterized query or update then passā€“ You can make a parameterized query or update, then pass in values for the placeholders ā€¢ Advantagesg ā€“ More convenient than string concatenation ā€“ Significantly faster with most drivers and databases If h l i d h l iblā€“ If the values contain user data, much less susceptible to SQL injection attacks 52
  • 26. Steps ā€¢ Make a placeholder A T bl h l (i d S i )ā€“ Assume someTable has two columns (int and String) String template = "INSERT INTO someTable VALUES(?, ?)"; P dSt t t i tPreparedStatement inserter = connection.prepareStatement(template); ā€¢ Substitute in values ā€“ Use setInt(index), setString(index), etc. Remember indices start with 1, not 0. for(ā€¦) {o ( ) { inserter.setInt(1, someInt); inserter.setString(2, someString) }} ā€¢ Execute command ā€¢ inserter.executeUpdate(); 53 Creating the Database ā€¢ Roles ā€“ Most JDBC developers do not need to create the database ā€“ That is the job of the database system admin Apache Derbyā€¢ Apache Derby ā€“ You can run Derby-specific scripts and create the database interactivelyy ā€“ Or, you can use Java and JDBC ā€¢ Using PreparedStatement simplifies the process Si l ā€œ D t b ā€ lā€¢ Simple ā€œmyDatabaseā€ example ā€“ Created with Java and JDBC Triggered from a ServletContextListener so databaseā€“ Triggered from a ServletContextListener so database creation code is executed at least once 54
  • 27. Creating Sample Database public class EmbeddedDbCreator { // Driver class not needed in JDBC 4 0 (Java SE 6)// Driver class not needed in JDBC 4.0 (Java SE 6) // private String driver = // "org.apache.derby.jdbc.EmbeddedDriver"; private String protocol = "jdbc:derby:";p g p j y private String username = "someuser"; private String password = "somepassword"; private String dbName = "myDatabase"; private String tableName = "employees"; private Properties userInfo; bli E b dd dDbC t () {public EmbeddedDbCreator() { userInfo = new Properties(); userInfo.put("user", username); userInfo put("password" password);userInfo.put( password , password); } 55 Creating Sample Database (Continued)(Continued) public void createDatabase() { Employee[] employees = {Employee[] employees { new Employee(1, "Larry", "Ellison", "CEO", 1234567890), new Employee(2, "Charles", "Phillips", "President",p y ( , , p , , 23456789), new Employee(3, "Safra", "Catz", "President", 32654987), ā€¦ }; 56
  • 28. Creating Sample Database (Continued)(Continued) try { String dbUrl = protocol + dbName + ";create=true";String dbUrl protocol + dbName + ;create true ; Connection connection = DriverManager.getConnection(dbUrl, userInfo); Statement statement = connection.createStatement(); String format = "VARCHAR(20)"; String tableDescription = String.format ("CREATE TABLE %s" +( CREATE TABLE %s + "(id INT, firstname %s, lastname %s, " + "position %s, salary INT)", tableName, format, format, format); statement.execute(tableDescription); 57 Creating Sample Database (Continued)(Continued) String template = String.format("INSERT INTO %s VALUES(?, ?, ?, ?, ?)",String.format( INSERT INTO %s VALUES(?, ?, ?, ?, ?) , tableName); PreparedStatement inserter = connection.prepareStatement(template); for(Employee e: employees) { inserter.setInt(1, e.getEmployeeID()); inserter.setString(2, e.getFirstName()); inserter setString(3 e getLastName());inserter.setString(3, e.getLastName()); inserter.setString(4, e.getPosition()); inserter.setInt(5, e.getSalary()); inserter.executeUpdate(); System.out.printf("Inserted %s %s.%n", e.getFirstName(), e.getLastName()); }} inserter.close(); connection.close(); 58
  • 29. Triggering Database Creation ā€¢ Database needs to be created once ā€“ Not for every request ā€“ Not even for every time server restarts Goalā€¢ Goal ā€“ Create table when Web app is loaded ā€¢ try/catch block in creation code halts process if tabletry/catch block in creation code halts process if table already exists ā€¢ Possible approaches S l i h i d i i i d b l i hā€“ Servlet with creation code in init, and web.xml with <load-on-startup>1</load-on-startup> ā€“ ServletContextListenerServletContextListener ā€¢ Same effect as above, but more straightforward ā€“ For desktop apps, just manually run the code once.59 Triggering Database Creation: ListenerListener package coreservlets; import javax.servlet.*; public class DatabaseInitializer implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { new EmbeddedDbCreator().createDatabase(); }} public void contextDestroyed(ServletContextEvent event) {} } 60
  • 30. Triggering Database Creation: web xmlweb.xml ā€¦ <listener><listener> <listener-class> coreservlets.DatabaseInitializer </listener-class> </listener> 61 Ā© 2010 Marty Hall Advanced Features Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 31. Transactions ā€¢ Idea ā€“ By default, after each SQL statement is executed the changes are automatically committed to the database ā€“ Turn auto-commit off to group two or more statementsā€“ Turn auto-commit off to group two or more statements together into a transaction ti tA t C it(f l )connection.setAutoCommit(false); ā€“ Call commit to permanently record the changes to the database after executing a group of statements ā€“ Call rollback if an error occurs 63 Transactions: Example Connection connection = DriverManager.getConnection(url, userProperties);g g ( , p ); connection.setAutoCommit(false); try { statement.executeUpdate(...); statement executeUpdate( );statement.executeUpdate(...); ... connection.commit(); } catch (Exception e) { try { connection.rollback(); } catch (SQLException sqle) { // report problem// report problem } } finally { try { ti l ()connection.close(); } catch (SQLException sqle) { } } 64
  • 32. Useful Connection Methods (for Transactions)(for Transactions) ā€¢ getAutoCommit/setAutoCommit ā€“ By default, a connection is set to auto-commit ā€“ Retrieves or sets the auto-commit mode commitā€¢ commit ā€“ Force all changes since the last call to commit to become permanentp ā€“ Any database locks currently held by this Connection object are released llb kā€¢ rollback ā€“ Drops all changes since the previous call to commit Releases any database locks held by this Connectionā€“ Releases any database locks held by this Connection object 65 Using JNDI and DataSource ā€¢ Idea ā€“ Use abstract name to get connection from a data source ā€¢ Advantages L h d i h h i dā€“ Lets you change data source without changing code ā€“ Available in multiple Web apps for network databases (not embedded Derby!)( y ) ā€¢ Disadvantage ā€“ Requires server-specific registration of data source ā€¢ Code for steps 1-3 replaced by: Context context = new InitialContext(); DataSource dataSource = (DataSource)context lookupDataSource dataSource = (DataSource)context.lookup ("java:comp/env/jdbc/dbName"); Connection connection = dataSource.getConnection(); 66
  • 33. DataSource: Tomcat Configuration (META-INF/context xml)(META-INF/context.xml) <?xml version="1.0" encoding="UTF-8"?> <Context><Context> <Resource name="jdbc/myDatabase" driverClassName="org apache derby jdbc ClientDriver"driverClassName="org.apache.derby.jdbc.ClientDriver" url="jdbc:derby:myDatabase" type="javax.sql.DataSource" " "username="someuser" password="somepassword" auth="Container" A ti "8" /maxActive="8" /> </Context> 67 More JDBC Options ā€¢ Stored procedures ā€¢ Changing buffer size ā€¢ Connection poolingp g ā€¢ Hibernate/JPA and other ORM tools ā€“ See tutorials at coreservlets.com ā€¢ JSP Standard Tag Library (JSTL) ā€“ Custom tags to hide JDBC details.g ā€¢ Some developers use JSTL to loop down the ResultSet. Disadvantage: ties presentation layer to JDBC. ā€¢ Some developers use JSTL to actually do queries Simpleā€¢ Some developers use JSTL to actually do queries. Simple. Disadvantage: very inflexible and violates MVC principle. 68
  • 34. Ā© 2010 Marty Hall Wrap-Up Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. JDBC and Derby References ā€¢ Books JDBC API T i l d R f b M d Fi hā€“ JDBC API Tutorial and Reference by Maydene Fisher, Jon Ellis, and Jonathan Bruce (Prentice Hall) ā€“ Expert Oracle JDBC Programming by R.M. Menon (APress) ā€“ JDBC Recipes: A Problem-Solution Approach by Mahmoud Parsian (APress)( ) ā€¢ Sun JDBC tutorial ā€“ http://java.sun.com/docs/books/tutorial/jdbc/ Derb referencesā€¢ Derby references ā€“ Derby beginnerā€™s tutorial ā€¢ http://db.apache.org/derby/papers/DerbyTut/g y y ā€“ Derby 10.4 manuals ā€¢ http://db.apache.org/derby/manuals/index.html#docs_10.4 70
  • 35. Summary 1. Load the driver N t i d i J 6 Cl f N th iā€“ Not required in Java 6; use Class.forName otherwise 2. Define the Connection URL ā€“ jdbc:vendor:blah (vendor gives exact format) 3. Establish the Connection ā€“ DriverManager.getConnection 4 Create a Statement object4. Create a Statement object ā€“ connection.createStatement 5. Execute a query ā€“ statement.executeQuery 6. Process the results ā€“ Loop using resultSet.next()Loop using resultSet.next() ā€“ Call getString, getInt, etc. 7. Close the connection 71 Ā© 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.