10 JDBC
10 JDBC
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. organization. Contact [email protected] for details. Developed and taught by well-known author and developer. At public venues or onsite at your location.
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 commands) Meta data Transaction control
5
Overview
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
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 accessing relational databases
API standardizes
Way to establish connection to database Approach to initiating queries Method to create stored (parameterized) queries The data structure of query result (table)
Determining the number of columns Looking up metadata, etc.
JDBC classes are in the java.sql package JDBC stands for Java DataBase Connectivity
7
On-line Resources
Suns JDBC Site
http://java.sun.com/javase/6/docs/technotes/guides/jdbc/
JDBC Tutorial
http://java.sun.com/docs/books/tutorial/jdbc/
JDBC Drivers
JDBC consists of two parts:
JDBC API, a purely Java-based API JDBC Driver Manager,which communicates with vendor-specific drivers that perform the real communication with the database.
Point: translation to vendor format is performed on the client
No changes needed to server Driver (translator) needed on client
9
Java Application
JDBC API
Database
Database
Java Type
boolean byte short int long float double byte[]
JDBC Type
NUMERIC DECIMAL DATE TIME TIMESTAMP CLOB BLOB ARRAY DISTINCT STRUCT REF JAVA_OBJECT
Java Type
BigDecimal java.sql.Date java.sql.Timestamp Clob Blob Array mapping of underlying type Struct Ref underlying Java class
String
10
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Dont return JDBC-specific (or Hibernate-specific) objects from the data-access layer
Return ordinary Java objects instead
2. 3. 4. 5. 6. 7.
Define the Connection URL Establish the Connection Create a Statement object Execute a query Process the results Close the connection
13
Examples
String host = "dbhost.yourcompany.com"; String dbName = "someName"; int port = 1234; String mySqlUrl = "jdbc:mysql//" + host + ":" + port + "/" + dbName; String embeddedDerbyUrl = "jdbc:derby" + dbName;
15
Statement types
Statement, PreparedStatement, CallableStatement
Details on other types given later
Example
Statement statement = connection.createStatement();
17
statement.executeUpdate("UPDATE "); statement.executeUpdate("INSERT "); statement.executeUpdate("DELETE"); statement.execute("CREATE TABLE"); statement.execute("DROP TABLE ");
String query = "SELECT col1, col2, col3 FROM sometable"; ResultSet resultSet = statement.executeQuery(query);
Example
18
resultSet.getString("columnName")
Returns value of column with designated name in current row, as a String. Also getInt, getDouble, getBlob, etc.
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)
Moves cursor to given row (starting with 1). Also last and afterLast.
19
20
Example
connection.close();
21
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Embedded mode
Database runs in same VM as Java app. Does not accept network connections. 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
23
http://db.apache.org/derby/
Username/password
Setup Summary
Setup summary
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
Creating database
Can 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
Creating database
Manually run database creation code. See Prepared Statements section for code, but this needs to be done once only. In most real apps, you have to query database, but someone else creates the database.
26
Creating database
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. In most real apps, you have to query database, but someone else creates the database.
Reminder: full code can be downloaded from http://courses.coreservlets.com/Course-Materials/ msajsp.html, so you can get db creation code there.
27
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 Connection Create a Statement object Execute a query Process the results Close the connection
Sample Database
Table name
employees
Column names
id (int). The employee ID. firstname (varchar/String). Employees given name. lastname (varchar/String). Employees family name. position (varchar/String). Corporate position (eg, ceo). salary (int). Yearly base salary.
Database name
myDatabase
Note
See Prepared Statements section for code that created DB
30
33
34
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 Connection Create a Statement object Execute a query Process the results Close the connection
36
Sample Database
Table name
employees
Column names
id (int). The employee ID. firstname (varchar/String). Employees given name. lastname (varchar/String). Employees family name. position (varchar/String). Corporate position (eg, ceo). salary (int). Yearly base salary.
Database name
myDatabase
Note
See Prepared Statements section for code that created DB
37
Goal
Build HTML table that shows all employees
Approach
Build HTML table directly in servlet
MVC combined with JSTL or custom tags might work better, but this lecture does not assume familiarity with those topics Basic JDBC code is the same either way
38
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 database independent.
39
40
41
44
45
Using MetaData
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
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.
System-wide data
connection.getMetaData().getDatabaseProductName() 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
49
50
(Parameterized Commands)
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
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 in values for the placeholders
Advantages
More convenient than string concatenation Significantly faster with most drivers and databases If values contain user data, much less susceptible to SQL injection attacks
52
Steps
Make a placeholder
Assume someTable has two columns (int and String)
String template = "INSERT INTO someTable VALUES(?, ?)"; PreparedStatement inserter = connection.prepareStatement(template);
Substitute in values
Use setInt(index), setString(index), etc. Remember indices start with 1, not 0.
for() { inserter.setInt(1, someInt); inserter.setString(2, someString) }
Execute command
inserter.executeUpdate();
53
Apache Derby
You can run Derby-specific scripts and create the database interactively Or, you can use Java and JDBC
Using PreparedStatement simplifies the process
56
57
Goal
Create table when Web app is loaded
try/catch block in creation code halts process if table already exists
Possible approaches
Servlet with creation code in init, and web.xml with <load-on-startup>1</load-on-startup> ServletContextListener
Same effect as above, but more straightforward
59
60
61
Advanced Features
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
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 together into a transaction
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); connection.setAutoCommit(false); try { statement.executeUpdate(...); statement.executeUpdate(...); ... connection.commit(); } catch (Exception e) { try { connection.rollback(); } catch (SQLException sqle) { // report problem } } finally { try { connection.close(); } catch (SQLException sqle) { } }
64
commit
Force all changes since the last call to commit to become permanent Any database locks currently held by this Connection object are released
rollback
Drops all changes since the previous call to commit Releases any database locks held by this Connection object
65
Advantages
Lets you change data source without changing code Available in multiple Web apps for network databases (not embedded Derby!)
Disadvantage
Requires server-specific registration of data source
67
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Derby references
Derby beginners tutorial
http://db.apache.org/derby/papers/DerbyTut/
Summary
1. Load the driver
71
Not required in Java 6; use Class.forName otherwise jdbc:vendor:blah (vendor gives exact format) DriverManager.getConnection connection.createStatement statement.executeQuery Loop using resultSet.next() Call getString, getInt, etc.
2. Define the Connection URL 3. Establish the Connection 4. Create a Statement object 5. Execute a query 6. Process the results 7. Close the connection
Questions?
JSF 2, PrimeFaces, Java 7, Ajax, jQuery, Hadoop, RESTful Web Services, Android, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training.
Developed and taught by well-known author and developer. At public venues or onsite at your location.