Professional Documents
Culture Documents
What is JDBC?
An API that lets you access virtually any tabular data source from the Java programming language
Whats an API? See J2SE documentation Whats a tabular data source? access virtually any data source, from relational databases to spreadsheets and flat files.
JDBC Documentation
General Architecture
What design pattern is implied in this architecture? What does it buy for us? Why is this architecture also multi-tiered?
Database Architectures
Two-Tier Architecture
simple client-side scripting offloads work onto the client fat client inflexible
Con:
Three-Tier Architecture
Three-Tier Pros
flexible: can change one part without affecting others can connect to different databases without changing code specialization: presentation / business logic / data management can cache queries can implement proxies and firewalls
Three-Tier Cons
higher complexity higher maintenance lower network efficiency more parts to configure (and buy)
N-Tier Architecture
Design your application using as many tiers as you need Use Object-Oriented Design techniques Put the various components on whatever host makes sense Java allows N-Tier Architecture, especially with RMI and JDBC
Relational Databases
invented by Dr. E.F.Codd data stored in records which live in tables maps row (record) to column (field) in a single table relation (as in relational) means row to column (not table to table)
Joining Tables
you can associate tables with one another allows data to nest allows arbitrarily complicated data structures not object-oriented
Join example
People
Addresses
SQL
Structured Query Language Standardized syntax for querying (accessing) a relational database Supposedly database-independent Actually, there are important variations from DB to DB
SQL Syntax
INSERT INTO table ( field1, field2 ) VALUES ( value1, value2 ) inserts a new record into the named table UPDATE table SET ( field1 = value1, field2 = value2 ) WHERE condition
removes all records that match condition SELECT field1, field2 FROM table WHERE condition
Transactions
Transaction = more than one statement which must all succeed (or all fail) together If one fails, the system must reverse all previous actions Also cant leave DB in inconsistent state halfway through a transaction COMMIT = complete transaction ROLLBACK = abort
JDBC Goals
SQL-Level 100% Pure Java Keep it simple High-performance Leverage existing database technology
Use strong, static typing wherever possible Use multiple methods to express multiple functionality
JDBC Architecture
Application JDBC Driver
Java code calls JDBC library JDBC loads a driver Driver talks to a particular database Can have more than one driver -> more than one database Ideal: can change database engines without changing any application code
21
22
Click Start, Settings, Control Panel, Administrative Tools, Data Sources, System DSN, and select Add
23
Select Microsoft Access Driver, Finish, type a name under Data Source Name, and hit Select
24
Navigate to the Samples directory of MS Office, select Northwind.mdb, hit OK, then hit OK in following two windows
25
1.Establish a connection 2.Create JDBC Statements 3.Execute SQL Statements 4.GET ResultSet 5.Close connections
27
1. Establish a connection
Class.forName("oracle.jdbc.driver.OracleDriver");
What do you think this statement does, and how? Dynamically loads a driver class, for Oracle database
What do you think this statement does? Establishes connection to database by obtaining a Connection object
28
29
String createLehigh = "Create table Lehigh " + "(SSN Integer not null, Name VARCHAR(32), " + "Marks Integer)"; stmt.executeUpdate(createLehigh); //What does this statement do? String insertLehigh = "Insert into Lehigh values + "(123456789,abc,100)"; stmt.executeUpdate(insertLehigh);
30
Get ResultSet
String queryLehigh = "select * from Lehigh"; ResultSet rs = Stmt.executeQuery(queryLehigh); //What does this statement do? while (rs.next()) { int ssn = rs.getInt("SSN"); String name = rs.getString("NAME"); int marks = rs.getInt("MARKS"); }
31
Close connection
stmt.close(); con.close();
32
JDBC allows SQL statements to be grouped together into a single transaction Transaction control is performed by the Connection object, default mode is auto-commit, I.e., each sql statement is treated as a transaction We can turn off the auto-commit mode with con.setAutoCommit(false); And turn it back on with con.setAutoCommit(true); Once auto-commit is off, no SQL statement will be committed until an explicit is invoked con.commit(); At this point all changes done by the SQL statements will be made permanent in the database.
33
Programs should recover and leave the database in a consistent state. If a statement in the try block throws an exception or warning, it can be caught in one of the corresponding catch statements E.g., you could rollback your transaction in a catch { } block or close database connection
34
35
36
public static void showEmployeeTable(String driver, String url, String username, String password) { try { // Load database driver if not already loaded. Class.forName(driver); // Establish network connection to database. Connection connection = DriverManager.getConnection(url, username, password); System.out.println("Employees\n" + "========="); Statement statement = connection.createStatement(); String query = "SELECT firstname, lastname FROM employees"; // Send query to database and store results. ResultSet resultSet = statement.executeQuery(query);
37
// Print results. while(resultSet.next()) { // First name System.out.print(resultSet.getString(1) + " "); // Last name System.out.println(resultSet.getString(2)); } } catch(ClassNotFoundException cnfe) { System.err.println("Error loading driver: " + cnfe); } catch(SQLException sqle) { System.err.println("Error connecting: " + sqle); } }
38
40
Metadata from DB
A Connection's database is able to provide schema information describing its tables, its supported SQL grammar, its stored procedures the capabilities of this connection, and so on
What is a stored procedure? Group of SQL statements that form a logical unit and perform a particular task
DatabaseMetaData dbmd = con.getMetaData(); String catalog = null; String schema = null; String table = sys% ; String[ ] types = null; ResultSet rs = dbmd.getTables(catalog , schema , table , types );
44
45