Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

1/22/2019

JDBC Introduction
• Standard Java library for accessing relational databases
– JDBC standardizes:
Database Access with JDBC • Establishing connection to database
• Approach to initiating queries
• Methods for creating stored (parameterized) queries
• The data structures for query results (table)
– Determining the number of columns, metadata, etc.
– API does not standardize SQL syntax
• JDBC is not embedded SQL
– JDBC classes are in the java.sql package

1 2

JDBC Drivers Steps in Using JDBC


 JDBC consists of two parts:
1. Load the JDBC driver
 The JDBC API, a purely Java-based 2. Define the Connection URL
API 3. Establish the Connection
 JDBC Driver Manager, which 4. Create a Statement object
communicates with vendor-specific
5. Execute a query
drivers that interact with the database
 Point: translation to vendor format is
6. Process the results
performed on the client 7. Close the connection
 No changes needed to server
 Driver (translator) needed on client

3 4

1
1/22/2019

JDBC Class Usage JDBC URLs


jdbc:subprotocol:source
DriverManager
 each driver has its own subprotocol
 each subprotocol has its own syntax for the source
Driver
jdbc:odbc:DataSource
 e.g. jdbc:odbc:Northwind
Connection jdbc:msql://host[:port]/database
 e.g. jdbc:msql://foo.nowhere.com:4333/accounting

Statement Jdbc:oracle:thin:@host:port:database
 jdbc:oracle:thin:@localhost:1521:ORCL

ResultSet

5 6

DriverManager Connection
DriverManager Method:
• A Connection represents a session with a specific database.
Connection getConnection (String url, String user, String password) • Within the context of a Connection, SQL statements are
executed and results are returned.
 Connects to given JDBC URL with given user name and
• Also provides “metadata” -- information about the database,
password
tables, and fields
 Throws java.sql.SQLException
 returns a Connection object
• Also methods to deal with transactions

7 8

2
1/22/2019

Obtaining a Connection Connection Methods


Statement createStatement()
 returns a new Statement object
String url = "jdbc:odbc:Northwind";
try { PreparedStatement prepareStatement(String
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); sql)
 returns a new PreparedStatement object
Connection con = DriverManager.getConnection(url);
} CallableStatement prepareCall(String sql)
catch (ClassNotFoundException e)  returns a new CallableStatement object

{ e.printStackTrace(); }
catch (SQLException e)
{ e.printStackTrace(); }

9 10

Using JDBC Statements Useful Statement Methods


 A Statement object is used for executing a static SQL • RessultSet executeQuery(String)
statement and obtaining the results produced by it. – Executes the SQL query and returns the data in a table (ResultSet)
– The resulting table may be empty but never null
– Through the Statement object, SQL statements are
ResultSet results = statement.executeQuery("SELECT a, b
sent to the database FROM table");
– Three types of statement objects are available: • int executeUpdate(String)
• Statement – Execute for INSERT, UPDATE, or DELETE statements
– For executing a simple SQL statement – Returns number of rows affected
– Supports Data Definition Language (DDL) statements CREATE
• PreparedStatement
TABLE, DROP TABLE and ALTER TABLE
– For executing a precompiled SQL statement passing in parameters
int rows = statement.executeUpdate("DELETE FROM
• CallableStatement EMPLOYEES WHERE STATUS=0");
– For executing a database stored procedure

11 12

3
1/22/2019

Useful Statement Methods(Cont’d) Prepared Statements


• execute • If executing similar SQL multiple times, using “prepared”
– Execute stored procedures, prepared statements (parameterized) statements may be more efficient
– Execution may or may not return a ResultSet (use
– Statement is created in standard form that is sent to the
statement.getResultSet). If the return value is true, two or more
result sets were produced database for compilation before actually being used
• getMaxRows/setMaxRows – Each time you use it, you simply replace some of the marked
– Maximum number of rows a ResultSet may contain parameters using the setXxx methods
– Unless explicitly set, the number of rows is unlimited (return value of • As PreparedStatement inherits from Statement, the
0)
corresponding execute methods have no parameters
• getQueryTimeout/setQueryTimeout
– execute(), executeQuery(), executeUpdate()
– Specifies the amount of a time a driver will wait for a STATEMENT
to complete before throwing a SQLException

13 14

Prepared Statement Example Callable Statements


Connection con = DriverManager.getConnection(url, user, password); • on the RDBMS server
PreparedStatement stmt = con.prepareStatement("UPDATE employees "+ – So-called “stored procedures”
"SET salary = ? " + "WHERE id = ?"); – Code created and maintained on server
int[] newSalaries = getSalaries();
– Benefit is performance, cost is yet another language to learn
int[] employeeIDs = getIDs();
for(int i=0; i<employeeIDs.length; i++) { • Stored procedures are like Java methods—they take input
statement.setInt(1, newSalaries[i]); parameters and can return results (possibly more than one)
statement.setInt(2, employeeIDs[i]); – Setup to pass parameters can be painful
statement.executeUpdate();
}

15 16

4
1/22/2019

ResultSet ResultSet Methods


• A ResultSet provides access to a table of data generated • boolean next()
by executing a Statement. – activates the next row
• Only one ResultSet per Statement can be open at once. – the first call to next() activates the first row

• The table rows are retrieved in sequence. – returns false if there are no more rows
• void close()
• A ResultSet maintains a cursor pointing to its current
– disposes of the ResultSet
row of data.
– allows you to re-use the Statement that created it
• The 'next' method moves the cursor to the next row. – automatically called by most Statement methods

17 18

ResultSet Methods ResultSet Methods


• Type getType(int columnIndex) • String getString(int columnIndex)
– returns the given field as the given type • boolean getBoolean(int columnIndex)
– fields indexed starting at 1 (not 0) • byte getByte(int columnIndex)
• Type getType(String columnName) • short getShort(int columnIndex)
• int getInt(int columnIndex)
– same, but uses name of field
• long getLong(int columnIndex)
– less efficient
• float getFloat(int columnIndex)
• int findColumn(String columnName) • double getDouble(int columnIndex)
– looks up column index given column name • Date getDate(int columnIndex)
• Time getTime(int columnIndex)
• Timestamp getTimestamp(int columnIndex)

19 20

5
1/22/2019

ResultSet Methods JDBC Class Diagram


• String getString(String columnName)
• boolean getBoolean(String columnName)
• byte getByte(String columnName)
• short getShort(String columnName)
• int getInt(String columnName)
• long getLong(String columnName)
• float getFloat(String columnName)
• double getDouble(String columnName)
• Date getDate(String columnName)
• Time getTime(String columnName)
• Timestamp getTimestamp(String columnName)

21 22

Using Microsoft Access via


Using Microsoft Access via ODBC ODBC (Continued)
 Database that comes preinstalled with Microsoft Office  Use sun.jdbc.odbc.JdbcOdbcDriver as the class name
 Click Start, Settings, Control Panel, Administrative Tools, Data of the JDBC driver.
Sources, System DSN, and select Add  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 Select Microsoft Access Driver, Finish, type a name under Data  Use "jdbc:odbc:Northwind" as the database address, and
Source Name, and hit Select use empty strings for the username and password.
 Navigate to the Samples directory of MS Office, select Connection connection =
Northwind.mdb, hit OK, then hit OK in following two DriverManager.getConnection("jdbc:odbc:Northwind", "","");
windows

23 24

6
1/22/2019

Example: Example: (cont’d)


import java.sql.*;
public class NorthwindTest { System.out.println("Employees\n" + "=========");
public static void main(String[] args) { Statement statement = connection.createStatement();
String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; String query = "SELECT firstname, lastname FROM employees";
String url = "jdbc:odbc:Northwind"; // Send query to database and store results.
String username = ""; ResultSet resultSet = statement.executeQuery(query);
String password = ""; // Print results.
showEmployeeTable(driver, url, username, password); while(resultSet.next()) {
} System.out.print(resultSet.getString(1) + " "); // First name
public static void showEmployeeTable(String driver, String url, String username, System.out.println(resultSet.getString(2)); // Last name
String password) { }
try { } catch(ClassNotFoundException cnfe) {
// Load database driver if not already loaded. System.err.println("Error loading driver: " + cnfe);
Class.forName(driver); } catch(SQLException sqle) {
// Establish network connection to database. System.err.println("Error connecting: " + sqle);
Connection connection = DriverManager.getConnection(url, }
username, password); }
}
25 26

Using JDBC MetaData ResultSetMetaData answers:


• What's the number of columns in the ResultSet?
• Metadata: “data about the data” • What's a column's name?
– Not “How many customers have sales over $100K?” but “How • What's a column's SQL type?
many columns have a datatype of BIT (boolean)?” • What's the column's normal max width in chars?
• What's the suggested column title for use in printouts and displays?
• System-wide data • What's a column's number of decimal digits?
– connection.getMetaData().getDatabaseProductName() • Does a column's case matter?
• Is the column a cash value?
– connection.getMetaData().getDatabaseProductVersion()
• Will a write on the column definitely succeed?
• Table-specific data • Can you put a NULL in this column?
• Is a column definitely not writable?
– resultSet.getMetaData().getColumnCount()
• Can the column be used in a where clause?
• When using the result, remember that the index starts at 1, not 0
• Is the column a signed number?
– resultSet.getMetaData().getColumnName() • Is it possible for a write on the column to succeed?
• and so on...

27 28

7
1/22/2019

DatabaseMetaData answers: Transactions


 What tables are available? • By default, after each SQL statement is executed the changes
 What's our user name as known to the database? are automatically committed to the database
– Turn auto-commit off to group two or more statements
 Is the database in read-only mode?
together into a transaction:
 If table correlation names are supported, are they restricted
to be different from the names of the tables? connection.setAutoCommit(false);
– Call commit to permanently record the changes to the database
 and so on…
after executing a group of statements
– Call rollback if an error occurs

29 30

Useful Transaction Methods Example:


Connection connection = DriverManager.getConnection(url, username, passwd);
connection.setAutoCommit(false);
• These methods apply to the Connection
try {
• getAutoCommit/setAutoCommit statement.executeUpdate(...);
– By default, a connection is set to auto-commit statement.executeUpdate(...);
connection.commit();
– Retrieves or sets the auto-commit mode } catch (Exception e) {
• Commit try {
connection.rollback();
– All changes since last commit to become permanent
} catch (SQLException sqle) {
– Database locks held by this Connection are released // report problem
• rollback }
} finally {
– Drops all changes since the previous call to commit try {
– Releases database locks held by this Connection object connection.close();
} catch (SQLException sqle) { }
}

31 32

You might also like