Date post: | 24-Dec-2015 |
Category: |
Documents |
Upload: | sheila-harris |
View: | 220 times |
Download: | 0 times |
241-301 Lab: JDBC 1
Computer Engineering Lab Computer Engineering Lab IIIIII
ObjectiveObjective– to give some background on JDBC to help wito give some background on JDBC to help wi
th the lab exercises th the lab exercises
241-301, Semester 1, 2009-2010
Introduction to Java Database Connectivity (JDBC)
241-301 Lab: JDBC 2
OverviewOverview
1. 1. What is JDBC?What is JDBC?
2. 2. The JDBC-ODBC BridgeThe JDBC-ODBC Bridge
3.3. Four Kinds of JDBC DriversFour Kinds of JDBC Drivers
4.4. JDBC PseudocodeJDBC Pseudocode
5.5. SimpleJDBCSimpleJDBC.java.java
Continued
241-301 Lab: JDBC 3
6.6. Meta DataMeta Data
7.7. Books.Books.accdbaccdb as an ODBC as an ODBC Data SourceData Source
8.8. TableTabless in in Books.Books.accaccdbdb
9.9. More InformationMore Information
241-301 Lab: JDBC 4
1. What is JDBC?1. What is JDBC?
JDBC is an interface which allows Java codJDBC is an interface which allows Java code to execute SQL statements inside relationae to execute SQL statements inside relational databasesl databases– the databases must follow the ANSI SQL-2 stanthe databases must follow the ANSI SQL-2 stan
darddard
241-301 Lab: JDBC 5
JDBC in UseJDBC in Use
Java program
connectivity
data processingutilities
JDBCdriver
for Oracle
driverfor Sybase
jdbc-odbcbridge
odbcdriver
241-301 Lab: JDBC 6
2. The JDBC-ODBC Bridge2. The JDBC-ODBC Bridge
ODBC (Open Database Connectivity) is a ODBC (Open Database Connectivity) is a Microsoft standard from the mid 1990’s.Microsoft standard from the mid 1990’s.
It is an API that allows C/C++ programs to It is an API that allows C/C++ programs to execute SQL inside databasesexecute SQL inside databases
ODBC is supported by many products.ODBC is supported by many products.
Continued
241-301 Lab: JDBC 7
The JDBC-ODBC bridge allows Java code tThe JDBC-ODBC bridge allows Java code to use the C/C++ interface of ODBCo use the C/C++ interface of ODBC– it means that JDBC can access many different dit means that JDBC can access many different d
atabase productsatabase products
The layers of translation (Java --> C --> SQThe layers of translation (Java --> C --> SQL) can slow down execution.L) can slow down execution.
Continued
241-301 Lab: JDBC 8
The JDBC-ODBC bridge comes The JDBC-ODBC bridge comes freefree with t with the JDK:he JDK:– called called sun.jdbc.odbc.JdbcOdbcDriversun.jdbc.odbc.JdbcOdbcDriver
The ODBC driver for Microsoft Access coThe ODBC driver for Microsoft Access comes with MS Officemes with MS Office– so it is easy to connect Java and Accessso it is easy to connect Java and Access
241-301 Lab: JDBC 9
3. Four Kinds of JDBC Driver3. Four Kinds of JDBC Driver
1. JDBC-ODBC Bridge1. JDBC-ODBC Bridge– translate Java to the ODBC APItranslate Java to the ODBC API
2. Native API2. Native API– translate Java to the database’s own APItranslate Java to the database’s own API
Continued
241-301 Lab: JDBC 10
3. Native Protocol3. Native Protocol– use Java to access the database more directly ususe Java to access the database more directly us
ing its low level protocolsing its low level protocols
4. Net Protocol4. Net Protocol– use Java to access the database via networking use Java to access the database via networking
middleware (usually TCP/IP)middleware (usually TCP/IP)– required for networked applicationsrequired for networked applications
241-301 Lab: JDBC 11
JDBC DriversJDBC Drivers
A searchable list of drivers (freeware, shareA searchable list of drivers (freeware, shareware, and commercial) can be found at:ware, and commercial) can be found at:
http://developers.sun.com/product/jdbc/drivershttp://developers.sun.com/product/jdbc/drivers
241-301 Lab: JDBC 12
4. JDBC PseudoCode4. JDBC PseudoCode
All JDBC programs do the following:All JDBC programs do the following:– 1) load the JDBC driver1) load the JDBC driver
– 2) Specify the name and location of the databas2) Specify the name and location of the database being usede being used
– 3) Connect to the database with a 3) Connect to the database with a ConnectionConnection objectobject
Continued
241-301 Lab: JDBC 13
– 4) Execute a SQL query using a 4) Execute a SQL query using a StatementStatement ob objectject
– 5) Get the results in a 5) Get the results in a ResultSetResultSet object object
– 6) Finish by closing the 6) Finish by closing the ResultSetResultSet, , StatemenStatemen
tt and and ConnectionConnection objects objects
241-301 Lab: JDBC 14
4.1. Pseudocode as a Diagram4.1. Pseudocode as a Diagram
DriveManager Connection Statement ResultSetcreates creates creates
Driver
SQL
SQL
data
data
make linkto driver
241-301 Lab: JDBC 15
4.2. DriveManager4.2. DriveManager
It is responsible for establishing the connectiIt is responsible for establishing the connection to the database through the driver.on to the database through the driver.
e.g.e.g.Class.forName(
"sun.jdbc.odbc.JdbcOdbcDriver");Connection conn = DriveManager.getConnection(url);
241-301 Lab: JDBC 16
4.3. Name the Database 4.3. Name the Database
The name and location of the database is giThe name and location of the database is given as a URLven as a URL– the details of the URL vary depending on the tythe details of the URL vary depending on the ty
pe of database that is being usedpe of database that is being used
241-301 Lab: JDBC 17
ODBC Database URLODBC Database URL
jdbc:odbc: //host.domain.com: 2048 /data/filejdbc:odbc: //host.domain.com: 2048 /data/file
The commsprotocol
The machineholding the database.
The portused for the connection.
The path tothe databaseon the machine
e.g. jdbc:odbc:Books
241-301 Lab: JDBC 18
4.4. Statement Object4.4. Statement Object
The The StatementStatement object provides a ‘workspace’ object provides a ‘workspace’ where SQL queries can be created, executed, anwhere SQL queries can be created, executed, and results collected.d results collected.
e.g.e.g.Statement st = Statement st =
conn.createStatement():conn.createStatement():ResultSet rs = st.executeQuery(ResultSet rs = st.executeQuery(
“ select * from Authors” );“ select * from Authors” );::
st.close();st.close();
241-301 Lab: JDBC 19
4.5. ResultSet Object4.5. ResultSet Object
Stores the results of a SQL query.Stores the results of a SQL query.
A A ResultSetResultSet object is similar to a ‘table object is similar to a ‘table’ of answers, which can be examined by ’ of answers, which can be examined by moving a ‘pointer’ (cursor).moving a ‘pointer’ (cursor).
Continued
241-301 Lab: JDBC 20
Cursor operations:Cursor operations:– first()first(),, last() last(), , next()next(), , previous()previous(), etc., etc.
Typical code:Typical code:while( rs.next() ) {while( rs.next() ) { // process the row; // process the row;}}
23
5
17
98
John
Mark
Paul
Peter
cursor
241-301 Lab: JDBC 21
5. 5. SimpleJDBCSimpleJDBC.java.java// SimpleJDBC.java// Displays the firstnames and lastnames// of the Authors table in the Books db.
import java.sql.*;
public class SimpleJDBC {
public static void main(String[] args) { // The URL for the Books database.
// ’Protected' by a login and password. String url = "jdbc:odbc:Books"; String username = "anonymous"; String password = "guest";
:
241-301 Lab: JDBC 22
try { // load the JDBC-ODBC Bridge driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// connect to db using DriverManager Connection conn =
DriverManager.getConnection( url, username, password );
// Create a statement object Statement statement = conn.createStatement();
// Execute the SQL query
ResultSet rs = statement.executeQuery( "SELECT lastName, firstName FROM Authors" );
:
241-301 Lab: JDBC 23
// Print the result set while( rs.next() )
System.out.println(
rs.getString("lastName") + ", " + rs.getString("firstName") );
// Close down statement.close(); conn.close(); }
:
241-301 Lab: JDBC 24
catch ( ClassNotFoundException cnfex ) { System.err.println( "Failed to load JDBC/ODBC driver." ); cnfex.printStackTrace(); System.exit( 1 ); // terminate program }
catch ( SQLException sqlex ) { System.err.println( sqlex ); sqlex.printStackTrace(); }
} // end of main()
} // end of SimpleJDBC class
241-301 Lab: JDBC 25
Section 7not done.
Section 7now done.
OutputOutput
241-301 Lab: JDBC 26
5.1. Username & Password5.1. Username & Password
The database’s link to the outside (e.g. its OThe database’s link to the outside (e.g. its ODBC interface) must be configured to have DBC interface) must be configured to have a login and passworda login and password– details for ODBC are given laterdetails for ODBC are given later
241-301 Lab: JDBC 27
5.2. Accessing a ResultSet5.2. Accessing a ResultSet
The The ResultSetResultSet class contains many metho class contains many methods for accessing the value of a column of thds for accessing the value of a column of the current rowe current row– can use the column name or positioncan use the column name or position– e.g. get the value in the lastName column:e.g. get the value in the lastName column:
rs.getString("lastName")
Continued
241-301 Lab: JDBC 28
The ‘tricky’ aspect is that the values are SQThe ‘tricky’ aspect is that the values are SQL data, and so must be converted to Java tyL data, and so must be converted to Java types/objects.pes/objects.
There are many methods for accessing/convThere are many methods for accessing/converting the data, e.g.erting the data, e.g.– getString(), getDate(), getInt(), getgetString(), getDate(), getInt(), getFloat(), getObject()Float(), getObject()
241-301 Lab: JDBC 29
6. Meta Data6. Meta Data
Meta data is the information Meta data is the information aboutabout the datab the database:ase:– e.g. the number of columns, the types of the cole.g. the number of columns, the types of the col
umnsumns– meta data is the meta data is the schemaschema information information
ID Name Course Mark
007 James Bond Shooting 99
008 Aj. Andrew Kung Fu 1
meta data
241-301 Lab: JDBC 30
6.1. Accessing Meta Data6.1. Accessing Meta Data
The The getMetaData()getMetaData() method can be used o method can be used on a n a ResultSetResultSet object to create its meta dat object to create its meta data object.a object.
e.g.e.g.ResultSetMetaData md = ResultSetMetaData md =
rs.getMetaData();rs.getMetaData();
241-301 Lab: JDBC 31
6.2. Using Meta Data6.2. Using Meta Data
int numCols = int numCols = md.md.getColumnCount();getColumnCount();
for (int i = 0; i <= numCols; i++) {for (int i = 0; i <= numCols; i++) { if (md.getColumnType(i) == if (md.getColumnType(i) ==
Types.CHAR)Types.CHAR) System.out.println( System.out.println(
md.getColumnName(i) )md.getColumnName(i) )}}
241-301 Lab: JDBC 32
6.3. More Meta Data Methods6.3. More Meta Data Methods
getTableName()getTableName() getPrecision()getPrecision()
– number of decimal digits in the columnnumber of decimal digits in the column isSigned()isSigned()
– returns true if column has signed numbersreturns true if column has signed numbers isCurrency()isCurrency() etc.etc.
241-301 Lab: JDBC 33
7. Books.7. Books.accaccdb as an ODBC Data Sourcedb as an ODBC Data Source
1. Click on1. Click on“Data“Data Sources Sources ((ODBCODBC)”)” in in “Administrative “Administrative Tools” folder in Tools” folder in tthe Controlhe ControlPanel.Panel.
241-301 Lab: JDBC 34
2. Press “Add’ to 2. Press “Add’ to add a data source add a data source and select and select Microsoft Access Microsoft Access Driver (*.mdbDriver (*.mdb,,*.accdb*.accdb). ). Press “Finish”.Press “Finish”.
241-301 Lab: JDBC 35
3. Type in a 3. Type in a source name, descriptiosource name, description, n, and press “Select” and press “Select” to browse to set to browse to set the path to the the path to the Books.Books.accaccdb db oror Books.mdb Books.mdb file.file.
Now click onNow click on“Advanced”.“Advanced”.
241-301 Lab: JDBC 36
4. Type in a username 4. Type in a username and password (guest).and password (guest).Click “Ok”Click “Ok”
241-301 Lab: JDBC 37
Two Access Database TypesTwo Access Database Types
In Access 2007, the standard database file In Access 2007, the standard database file format is ".accdb"format is ".accdb"– use use Books.accdbBooks.accdb if you have Access 2007 on your if you have Access 2007 on your
machinemachine
In earlier versions of Access (e.g. Access In earlier versions of Access (e.g. Access 2003), the file format was ".mdb"2003), the file format was ".mdb"– use use Books.mdbBooks.mdb if you have an earlier version of if you have an earlier version of
Access on your machineAccess on your machine
241-301 Lab: JDBC 38
8. Table8. Tabless in Books. in Books.accaccdbdb(and Books.mdb)
241-301 Lab: JDBC 39
9. More Information9. More Information
Ivor Horton’s Beginning Java 2, JDK 5 Edition, Ivor Horton’s Beginning Java 2, JDK 5 Edition, Wiley Publishing, 2005Wiley Publishing, 2005Chapters Chapters 24 24 and and 25 (starts on p.1306)25 (starts on p.1306)
Advanced Java 2 Platform: How to Program Advanced Java 2 Platform: How to Program Deitel & Deitel, Prentice-Hall, Deitel & Deitel, Prentice-Hall, 20012001Chapter Chapter 88
http://java.coe.psu.ac.th/ForMember/
Continued
241-301 Lab: JDBC 40
Current Information:Current Information:http://java.sun.com/javase/technologies/database/index.jsp
The Java Documentation and tutorialThe Java Documentation and tutorial– http://java.sun.com/docs/books/tutorial/
– the the JDBC Database Access JDBC Database Access ‘trail’ is very good‘trail’ is very good