Sie sind auf Seite 1von 36

Java Database Connectivity

JDBC Overview
Recipe for a Basic JDBC application

JDBC A closer look


Executing a query to get data
Result Set Processing ResultSet Metadata

Mapping SQL type to Java types Updating a Table Error and Warnings PreparedStatement Database Metadata Transactions JDBC 2.0 and 3.0

Appendix
Setting up ODBC with MS Access
Copyright Objective Consulting JDBC 1

JDBC - Basics
Database Management Systems (DBMS), usually simply referred as databases, provide data storage and data management for applications with large volumes of data. Example databases (DBMSs) are Oracle, Sybase, IBM UDB, MS SQL Server, MS Access. The common feature of most databases is that they support the Structured Query Language (SQL). SQL provides commands for creating, reading, and updating database tables. JDBC makes possible
The development of Java, therefore portable, programs to access any SQL compliant database. Development of optimized low-level database specific drivers by DB vendors and third-party developers.

Copyright Objective Consulting

JDBC 2

JDBC Basics MS Access DBMS

Copyright Objective Consulting

JDBC 3

JDBC Sample Table


Fdfafd

Copyright Objective Consulting

JDBC 4

JDBC - Basics
JDBC is a Java language API that provides access to databases which utilize the Structured Query Language (SQL). JDBC drivers which implement the JDBC API must support at least SQL-92. The result is that SQL DB applications can be entirely written in Java. The majority of the code of these applications can be database neutral by utilizing the SQL that is not vendor specific.

Copyright Objective Consulting

JDBC 5

JDBC - Basics
Java application
JDBC API

JDBC Driver Manager


JDBC Driver API
JDBC/ODBC

Bridge

Vendorsupplied JDBC driver

3rd party JDBC driver

ODBC driver

Database

Sybase Database

Oracle Database
JDBC 6

Copyright Objective Consulting

JDBC - Basics
JDBC drivers are categorized into 4 types.
Type 1: JDBC-ODBC Bridge Drivers Type 2: Native-API (partly Java) Drivers Type 3: Net-Protocol All-Java Middleware Drivers Type 4: Native-protocol All-Java Drivers

Type 1 JDBC-ODBC bridge drivers are useful for testing and very small desktop systems only. Most database venders supply a type 3 or type 4 driver.
Copyright Objective Consulting JDBC 7

JDBC - Basics
Most DB vendors supply a JDBC driver with their DBMS. You can also purchase a 3rd party driver. Driver selection is based on the architecture of the application (1-tier vs 3-tier) and tradeoffs of speed, portability, reliability. The examples in this presentation use the JDBCODBC driver that comes with the JDK.
For a comprehensive list of JDBC drivers see Suns web site http://java.sun.com/products/jdbc/jdbc.drivers.html

Copyright Objective Consulting

JDBC 8

JDBC - Basics
Client
Client (Visual presentation)

HTTP, RMI,etc..
Middle tier (business logic)

JDBC

JDBC
Database protocol Database protocol Database Database

Single tier application

Three tier application


Copyright Objective Consulting JDBC 9

JDBC The Basic Recipe


Here are the steps for a basic JDBC recipe Step 1 - Load the driver Step 2 - Create a database connection Step 3 - Create a statement Step 4 - Execute the statement(s) Step 5 - Process the results Step 6 - Close the resources

Copyright Objective Consulting

JDBC 10

Recipe Step 1 - Loading a Driver


The driver(s) must be registered with the DriverManager. The most common used method is to manually load it.
import java.sql.*; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); Class.forName(com.oracle.jdbc.OracleDriver").newInstance(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } // two drivers now registered with the DriverManager The driver is supplied by the vendor and must be on the classpath. The driver class name(s) can be read from a config file (Java properties or XML) instead of hard coding in the application

An alternate method of loading the driver is via a properties file.


Copyright Objective Consulting JDBC 11

Recipe JDBC URLs


JDBC Drivers use URLs to identify and connect to a particular database. The general syntax for the URL is jdbc:driver:databasename Some examples
static final String url_1 static final String url_2 = "jdbc:odbc:ExampleDB_JavaCourse"; = "jdbc:pointbase:SOME_DB";

The portion after jdbc: is database specific. Consult the docs for your specific database.

Copyright Objective Consulting

JDBC 12

Recipe Step 2 Create a Connection


Create an instance of a Connection by using the getConnection() from the DriverManager. The arguments required are: a database URL, userid and password.
import java.sql.*; static final String url = "jdbc:odbc:ExampleDB_JavaCourse"; static final String user = guest"; static final String password = guestpassword"; Connection dbConnection = DriverManager.getConnection(url, user, password);

The DriverManager will select the appropriate driver and setup the DB connection. If the DB does not require a user and password then use blanks.
static final String user = "; static final String password = ";
Copyright Objective Consulting JDBC 13

Recipe Step 2 Create a Connection


Setting up a connection is time consuming.
Connection dbConnection = DriverManager.getConnection(url, user, password);

A common technique is to create the connection during program initialization and use it throughout the life of the application. Tear down the connection upon program exit.

Copyright Objective Consulting

JDBC 14

Recipe Step 3 - Create a statement


There are three JDBC statement classes.

Statement
Basic SQL statements

PreparedStatement
Precompiled SQL for improved performance

CallableStatement
To execute stored procedures in the database

For now we will look at the Statement class use to execute basic SQL statements.
Copyright Objective Consulting JDBC 15

Recipe Step 3 - Create a statement


A JDBC Statement object has methods that can be used to:
execute SQL queries (SELECT) execute SQL updates (INSERT, UPDATE, DELETE) and data definition commands (CREATE TABLE, DROP TABLE) execute an arbitrary SQL statement (any of the above)

In the next examples we will use a Statement object to execute SQL queries.

Copyright Objective Consulting

JDBC 16

Recipe Step 3 - Create a statement


import java.sql.*; static final String url = "jdbc:odbc:ExampleDB_JavaCourse"; static final String user = "; static final String password = "; // Step 1 load the driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } // Step 2 create a Connection object Connection dbConnection = DriverManager.getConnection(url, user, password);

// Step 3 create a Statement object Statement stmt = dbConnection.createStatement();

Copyright Objective Consulting

JDBC 17

Recipe Step 4 - Execute a statement


import java.sql.*; . // Step 2 create a Connection object Connection dbConnection = DriverManager.getConnection(url, user, password); // Step 3 create a Statement object Statement stmt = dbConnection.createStatement();

// // //

// Step 4 use the Statement object to execute SQL stmt.executeQuery(anSQLquery); stmt.executeUpdate(anSQLupdate); stmt.execute(anSQLstatement); // a query or update

Copyright Objective Consulting

JDBC 18

Recipe Step 4 - Execute a statement


Executing a query is an operation frequently performed on a database so will use this as our example. The result of executing this query is that a result set containing the requested information will be returned. // Step 3 create a Statement object Statement stmt = dbConnection.createStatement();
// Step 4 use the Statement object to execute SQL

String query = select firstname from students; ResultSet rs = stmt.executeQuery(query);

Copyright Objective Consulting

JDBC 19

Recipe Step 5 - Processing a Result Set


// Step 3 create a Statement object Statement stmt = dbConnection.createStatement(); // Step 4 use the Statement object to execute SQL String query = select FirstName from students;

ResultSet rs = stmt.executeQuery(query);
// Step 5 process the results row by row while( rs.next() ) { System.out.println(rs.getString(FirstName)); }

A result set can be viewed as a table of data containing rows as a result of a query. The cursor is initially positioned before the first row. The columns returns are those specified in the query.
Copyright Objective Consulting JDBC 20

10

Recipe Step 6 - Closure


At program termination we would close the objects to ensure that database resources are released.
Connection dbConnection = DriverManager.getConnection(url, user, password); Statement stmt = dbConnection.createStatement(); String query = select FirstName from students; ResultSet rs = stmt.executeQuery(query); while(rs.next()) { System.out.println(rs.getString(FirstName)); }

rs.close(); stmt.close(); dbConnection.close();


Copyright Objective Consulting JDBC 21

JDBC Recipe - Example

Copyright Objective Consulting

JDBC 22

11

JDBC Recipe - Example

Copyright Objective Consulting

JDBC 23

The Basic Recipe - Summary


The steps for a basic JDBC program 1. Load the driver register with DriverManager
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").

2. Create a database connection


Connection dbConnection = DriverManager.getConnection(url, user, password);

3. Create a statement
Statement stmt = dbConnection.createStatement();

4. Execute the statement(s)


stmt.executeQuery(query); stmt.executeUpdate(anUpdate);

5. Process the results 6. Close


rs.close(); stmt.close(); dbConnection.close();
Copyright Objective Consulting JDBC 24

12

JDBC A Closer Look


Now that we have seen the overview and the basic recipe we will take a closer look.
Executing a query to get data
Result Set Processing ResultSet Metadata

Mapping SQL type to Java types Updating a Table Error and Warnings PreparedStatement Database Metadata Transactions JDBC 2.0 and 3.0

Appendix
Setting up ODBC with MS Access
Copyright Objective Consulting JDBC 25

JDBC - ResultSet
Executing an SQL query returns a ResultSet The ResultSet can be viewed as a table containing the columns specified in the query. The cursor is initially positioned before first row. In JDBC 1.0 the result set can be traversed only in the forward direction via the next() method.
The result set can be traversed only once

In JDBC 2.0 ResultSets can be traversed in both directions We will focus on JDBC 1.0 features since they are common to all applications and your DB may not have a JDBC 2.0 compliant driver or you may have to maintain older code.
Copyright Objective Consulting JDBC 26

13

Traversing a Result Set JDBC 1.0


String query = select FirstName from students;

ResultSet rs = stmt.executeQuery(query);
// Step 5 process the results row by row while(rs.next()) { System.out.println(rs.getString(FirstName)); }

A result set is a table of data containing rows as a result of a query. The cursor is initially positioned before the first row. The columns returns are those specified in the query.
Copyright Objective Consulting JDBC 27

Processing a ResultSet Getting Data


The data in the table/result set are SQL data types. When a value is retrieved it is converted to a Java type. Individual columns values are read using one of the getXXX() methods. (e.g. getString(), getLong(), getDate(), etc.) There are two versions of each getXXX() method:
one that takes the case-insensitive String name of the column one that takes an SQL-style column index; column numbers begin at 1
// Process the results row by row while(rs.next()) { text = rs.getString(1); text = rs.getString(firstname); }
Copyright Objective Consulting JDBC 28

14

ResultSet Getting Data


// Example using getString(col_num) and getString(col_name)
String text; String query = select firstName, lastname from students; ResultSet rs = stmt.executeQuery(query); // Process the results row by row while(rs.next()) { text = rs.getString(1); text = rs.getString(firstname); }

Getting the data using the column number is more efficient. However if the SQL query column order changes the index will have to be changed; this is not required if retrieving using column names. Columns should be processed from left to right otherwise you may encounter errors.
Copyright Objective Consulting JDBC 29

Getting Data Generically


Each getXXX() method will make reasonable type conversions when the type of the method does not match the type of the column. For example, rs.getString(Price) converts the floating-point value of a Price column to a string. The type conversions are performed by the JDBC driver. getObject() is the most generic of the getXXX() methods. getString() is fairly generic
// Price column contains a SQL FLOAT (java.sql.Types.FLOAT) float priceAsPrimitive; String priceAsString; Float priceAsFloat; while(rs.next()) { priceAsString = rs.getString(Price); priceAsPrimitive = rs.getFloat( Price); priceAsFloat = rs.getObject(Price); }
Copyright Objective Consulting JDBC 30

15

ResultSet Getting Data


The following table lists some of the getXXX() methods and the mapping between SQL data type, Java type and the type return by the getXXX() method. These are the default mappings according to the JDBC 1.0 specification. Some drivers do not follow this mapping exactly. Consult the documentation that comes with your driver. 2nd column shows the Java type returned from the getObject() method and most of the getXXX() methods. When the getXXX() method returns a primitive instead of an Object it is listed in the 2nd column in parentheses.

Copyright Objective Consulting

JDBC 31

Getting Data SQL to Java type mapping


SQL Data Type
CHAR VARCHAR LONGVARCHAR NUMERIC DECIMAL BIT TINYINT SMALLINT INTEGER BIGINT REAL

Java Type
String String String java.math.BigDecimal java.math.BigDecimal Boolean (boolean) Integer (byte) Integer (short) Integer (int) Long (long) Float (float)
Copyright Objective Consulting

getXXX() method
getString() getString() getString() getBigDecimal() getBigDecimal() getBoolean() getByte() getShort() getInt() getLong() getFloat()
JDBC 32

16

Getting Data SQL to Java type mapping


SQL Data Type
FLOAT DOUBLE BINARY VARBINARY LONGVARBINARY DATE TIME TIMESTAMP

Java Type
Double Double byte[] byte[] byte[] java.sql.Date java.sql.Time java.sql.Timestamp (double) (double)

getXXX() method
getDouble() getDouble() getBytes() getBytes() getBytes() getDate() getTime() getTimestamp()

Note: java.sql.Date is not java.util.Date

Copyright Objective Consulting

JDBC 33

JDBC ResultSet Metadata


Metadata is data about data. The result set metadata contains information about the columns in the result set. The metadata can be queried to determine information about any column such as:
the name of the column E.g. rsmd.getColumnName(1); //col 1 the normal maximum display width whether it is readOnly or writable whether or not it supports null values

These methods are useful to writing generic display methods and for preventing errors. The result set metadata also has a method to determine how many columns were returned. Next we will see a simple example.
Copyright Objective Consulting JDBC 34

17

ResultSet Metadata Column position


Note that the position of columns in a result set are not necessarily the same as those of the DB table.

Copyright Objective Consulting

JDBC 35

ResultSet Metadata Simple Example


ResultSet rs = stmt.executeQuery(query); displayResult(rs); .. public void displayResult(ResultSet rs) { ResultSetMetaData rsmd = rs.getMetaData(); int numCols = rsmd.getColumnCount(); theResultPane.setText(""); while (rs.next()) { theResultPane.append("\n"); for (int i = 1; i <= numCols; i++) { String text = rs.getString(i); if (text == null) text = ""; theResultPane.append(text + ":"); } } rs.close(); }
Copyright Objective Consulting

JDBC 36

18

JDBC Updating a Table


A JDBC Statement object has methods that can be used to:
execute SQL queries (SELECT)

execute SQL updates (INSERT, UPDATE, DELETE) and


data definition commands (CREATE TABLE, DROP TABLE) execute an arbitrary SQL statement (any of the above)
// // // stmt.executeQuery(anSQLquery); stmt.executeUpdate(anSQLupdate); stmt.execute(anSQLstatement); // a query or update

In the next examples we will use a Statement object to execute SQL updates.

Copyright Objective Consulting

JDBC 37

JDBC Updating a Table


Column names and values used in example Note the value of Phils e-mail address

Copyright Objective Consulting

JDBC 38

19

JDBC - statement.executeUpdate()
A Java program to find the row with the matching first name and update the e-mail address column in the table.

Copyright Objective Consulting

JDBC 39

JDBC - statement.executeUpdate()
Query shows that the table was updated

Copyright Objective Consulting

JDBC 40

20

JDBC - statement.executeUpdate()
public void actionPerformed(ActionEvent evt) { String name = theName.getText(); String email = theEmail.getText(); String SQLupdate = "Update Students Set emailname = '" + email + "' " + "Where FirstName = '" + name + "'"; // single quotes Statement stmt = theConnection.createStatement(); int n = stmt.executeUpdate(SQLupdate); if (n == 0) { System.out.println(No rows updated); }

Copyright Objective Consulting

JDBC 41

JDBC - statement.executeUpdate()
public void actionPerformed(ActionEvent evt) { String name = theName.getText(); String email = theEmail.getText(); String SQLupdate = "Update Students Set emailname = '" + email + "' "+ "Where FirstName = '" + name + "'"; Statement stmt = theConnection.createStatement(); int n = stmt.executeUpdate(SQLupdate); if (n == 0) { System.out.println(No rows updated); }

Copyright Objective Consulting

JDBC 42

21

JDBC Errors and Warnings


Errors and warnings can be generated and thrown by the JDBC objects such as Connection, Statement and ResultSet. The hierarchy is:
+ java.lang.Exception + java.sql.SQLException + java.sql.SQLWarning + java.sql.DataTruncation

Copyright Objective Consulting

JDBC 43

JDBC Errors and Warnings


When a serious error occurs a SQLException object is created and thrown.

A SQLException provides the following information:


A description of the error. This is printed in stack traces. A "SQLstate" string, which follows the XOPEN/SQL-92 SQLstate conventions. An integer error code. Usually this will be the actual error code returned by the underlying database. A chain to a next Exception. This can be used to provide additional error information.

Useful methods
String String int SQLException getMessage(); getSQLState(); getErrorCode(); getNextException();
Copyright Objective Consulting JDBC 44

22

JDBC Errors and Warnings


Error handling example
try { Connection dbConnection = DriverManager.getConnection(url,user,password); String query = SELECT * From A_Table; Statement stmt = dbConnection.createStatement(); ResultSet rs = stmt.executeStatement(query); } catch( SQLException se) { while(se != null) { System.out.println(Message: System.out.println(SQLState: + ex.getMessage()); + ex.getSQLState());

System.out.println(Vendor Code: + ex.getErrorCode()); System.out.println(----------------------------------------); se = se.getNextException(); } } Copyright Objective Consulting JDBC 45

JDBC Errors and Warnings


When a less serious error occurs a SQLWarning is created but not thrown; you must explicitly check for the warning. Warnings can be queried from a Connection, Statement, or ResultSet.
printWarnings(dbConnection.getWarnings()); printWarnings(stmt.getWarnings()); printWarnings(rs.getWarnings()); private printWarnings(SQLWarning w) { while (w! = null) { System.out.println(SQLState: System.out.println(Message: w = w.getNextWarning(); } } + w.getSQLState()); + w.getMessage());

System.out.println(Vendor Code: + w.getErrorCode());

Copyright Objective Consulting

JDBC 46

23

JDBC Errors and Warnings


A DataTruncation can occur during a read or a write. If it occurs during a read then a warning is generated. If it occurs during a write then an exception is thrown.
int getDataSize() Gets the number of bytes of data that should have been transferred. int getIndex() Retrieves the index of the column or parameter that was truncated. boolean getParameter() Indicates whether the value truncated was a parameter value or a column value. boolean getRead() Indicates whether or not the value was truncated on a read. int getTransferSize() Gets the number of bytes of data actually transferred.
Copyright Objective Consulting JDBC 47

JDBC - PreparedStatement
Recall that there are three JDBC statement classes. Statement
Basic SQL statements

PreparedStatement
Precompiled SQL for improved performance CallableStatement
To execute stored procedures in the database

Now we will look at the PreparedStatement class which is used to improve performance.
Copyright Objective Consulting JDBC 48

24

JDBC - PreparedStatement
When the database engine executes a SQL query via executeQuery() it must process the SQL statement. Processing includes parsing and optimizing the SQL statement.
Parsing checking syntax, are the objects (table names, etc) in the DB, are the data conversion legal Optimizing finding the best access path

If the SQL statement is used frequently then doing the overhead processing in advance (preparing) can improve performance. (approx. 2 to 10 times faster depending on the the
complexity of the SQL statement, number of iterations, etc.)

Copyright Objective Consulting

JDBC 49

JDBC - PreparedStatement
The Connection object performs the parsing/preparation. The PreparedStatement has place-holders for the parameters that will be used when the statement is executed. The values for the parameters are set using one of the setXXX() methods. Assume we have a table to keep track of student assignments. The value of an assignment is a grade. We want to get the value of all assignments for a given student.
String query1 = select assgn1, assgn2, assgn3 from studentAssignments where firstname = ? and lastname = ?; PreparedStatement ps1 = conn.prepareStatement(query1); ps1.setString(1, John); ps1.setString(2, Doe); ResultSet rs = ps1.executeQuery();
Copyright Objective Consulting JDBC 50

25

JDBC - PreparedStatement
The values of parameters set via the setXXX() methods is preserved after the statement is executed. This is convenient if some of the values do not change before the next execution. However you may want to clear the values.
// Get values from JTextFields on a GUI
String firstName = textFieldFirstName.getText(); String lastName = textFieldLastName.getText();

// Set values of substitution variables


ps1.setString(1, firstName); ps2.setString(2, lastName); ResultSet rs = ps1.executeQuery();

// Now clear up the values


ps1.clearParameters();
Copyright Objective Consulting JDBC 51

JDBC - Transactions
There are situations in which we must treat a number of DB operations (queries, updates) as an atomic action.
Must update more than one table. If one update fails then want to back out change changes that have already been posted. Two users/threads may be operating on the same set of data. Similar to synchronizing threads, create an atomic action.

These atomic actions are achieved by using Transactions.


Copyright Objective Consulting JDBC 52

26

JDBC - Transactions
A transactions consists of a group of operations.
The transactions is only permanently posted to the database if it is committed. If the program terminates abnormally the transaction is automatically rolled back. By default each JDBC operations occur in a transaction that is automatically committed.
try { conn.setAutoCommit(false);// default commits each operation stmt.executeQuery(aQuery); stmt.executeUpdate(updateOne); stmt.executeQuery(updateTwo); conn.commit(); // Commit the transaction } catch( SQLException se) { conn.rollback(); // back out changes temporarily posted }
Copyright Objective Consulting JDBC 53

JDBC - Transactions
Databases support various transaction isolation levels. An isolation level defines when db changes become visible to other transactions. JDBC defines 5 isolation levels. The underlying database defines which levels are supported. The default isolation level depends on the driver. Consult your DB and driver documentation.
Example: Minimal transaction isolation allow dirty reads. Other transactions can see the results of SQL operations before the transaction is committed. If the transaction is rolled back other transactions will be left with invalid data.

try { conn = DriverManager.getConnection(DB_URL, USER, PASSWD); conn.setTransactionIsolationLevel( Connection.TRANSACTION_READ_UNCOMMITTED); conn.setAutoCommit(false);// default commits each operation . } catch( SQLException se) { conn.rollback(); // back out changes temporarily posted }

Copyright Objective Consulting

JDBC 54

27

JDBC - Transactions
Note that each transaction requires a connection object. Therefore, multiple transactions require multiple connections. Options are:
Create a connection fore each client request
This can be too time consuming. Ok for transactions that occur infrequently and for which the overhead of creating connection is acceptable. Not scalable

Create a number of connections in advance (do connection pooling) Use JDBC 2.0 connection pooling
Copyright Objective Consulting JDBC 55

JDBC Database Metadata

Copyright Objective Consulting

JDBC 56

28

JDBC Database MetaData


Recall that a ResultSet has associated metadata that can be queried to determine information about columns (e.g. getColumnType(), getColumnName(), isReadonly(), isCaseSensitive, etc.) and the the result set as a whole via getColumnCount().
ResultSet rs = stmt.executeQuery(query); ResultSetMetaData rsmd = rs.getMetaData(); int numCols = rsmd.getColumnCount();

We can get detailed information about the database (set of tables) as a whole using the DatabaseMetadata.

Copyright Objective Consulting

JDBC 57

JDBC Database MetaData


We can obtain detailed information about the database as a whole using the DatabaseMetaData. The DatabaseMetaData interface supports numerous methods. Some methods return ResultSet objects therefore ResultSet methods are used to obtain that information. If the driver does not support the metadata query then a SQLException is thrown.
Example: Obtaining the driver used and the list of tables in a database.

Connection conn = DriverManager.getConnection(DB_URL, ,); DatabaseMetaData dbMD = conn.getMetaData(); System.out.println(Driver: + dbMD.getDriverName()); String[] tableTypes = { TABLE }; ResultSet allTables = dbMd.getTables(null,null,null,tableTypes); while(allTable.next()) { String tableName = allTables.getString(TABLE_NAME); System.out.println(Table Name: + tableName); } Copyright Objective Consulting JDBC 58

29

JDBC JDBC 2.0 and 3.0


JDBC 2.0 (since 1.2) Result Sets are scrollable (forward and backward) Results Sets are updateable (setUpdateXXX() methods) Batch updates (e.g. inserting many rows in the DB) Connection Pooling Support for BLOBs and CLOBs Support for SQL User Defined Types by specifying mapping between the UDTs and Java objects. JDBC 3.0 (since 1.4) NEW see Suns web site.

Copyright Objective Consulting

JDBC 59

JDBC Summary/Review
We have seen the following topics: JDBC Overview
Recipe for a Basic JDBC application

JDBC A closer look


Executing a query to get data
Result Set Processing ResultSet Metadata

Mapping SQL type to Java types Updating a Table Error and Warnings PreparedStatement Database Metadata Transactions JDBC 2.0 and 3.0 BONUS Appendix to help you setup ODBC to play @ home.
Copyright Objective Consulting JDBC 60

30

Appendix MS-Access example


Trying this at home
This example shows how to setup ODBC access. Obtain MS-Access or an Access DB and the Access runtime components. The JDBC-ODBC driver comes with the JDK. The JDBC-ODBC driver supports only JDBC 1.0
there may be a JDBC 2.0 driver in the future

The ODBC driver is included with the Windows OS. Alternatively you could try setup MySQL (www.mysql.org)

Copyright Objective Consulting

JDBC 61

JDBC Sample Table


The sample table and code is on Phils website

Copyright Objective Consulting

JDBC 62

31

JDBC - ODBC
Control Panel Double-click the ODBC data sources applet.

Copyright Objective Consulting

JDBC 63

JDBC - ODBC
Click on User Data Source Name (DSN) or System DSN tab. All existing Data Sources will be displayed.

Copyright Objective Consulting

JDBC 64

32

JDBC - ODBC
I chose User DSN for this example. Choose a driver. See next slide.

Copyright Objective Consulting

JDBC 65

JDBC ODBC MS-Access


Select the driver and then click Finish

Copyright Objective Consulting

JDBC 66

33

JDBC - ODBC
Choose the Data Source Name This will be used in your code as part of the DB URL.

Copyright Objective Consulting

JDBC 67

JDBC - ODBC
Make the link between the DSN and the database by selecting the database. Press OK

Copyright Objective Consulting

JDBC 68

34

JDBC - ODBC
The Database is now listed. Press OK. Done.

Copyright Objective Consulting

JDBC 69

JDBC - ODBC
The Data Source Name is now in the list of user or system DSNs.

Copyright Objective Consulting

JDBC 70

35

JDBC - ODBC
This example shows how to setup ODBC access. Obtain MS-Access or an Access DB and the Access runtime components. The JDBC-ODBC driver comes with the JDK. The JDBC-ODBC driver supports only JDBC 1.0
there may be a JDBC 2.0 driver in the future

The ODBC driver is included with the Windows OS. Alternatively you could try setup MySQL (www.mysql.org)
Copyright Objective Consulting JDBC 71

36

Das könnte Ihnen auch gefallen