Sie sind auf Seite 1von 57

1

JDBC ver 1.0

JDBC: An Intro
jdbc is a generic SQL database access framework in Java allows applications to query databases, and manipulate data returned from them it is based on X/Open SQL Call Level Interface(CLI) standard (ODBC is also based on the CLI)

JDBC ver 1.0

Jdbc
Advantages Leverage existing enterprises Reduced Development time zero configuration for network clients Key Features Full access to Metadata No installation Database connection identified by URL style Included in the java platform
3 JDBC ver 1.0

JDBC( Drivers )
JDBC-ODBC Bridge (Type 1) Native-API partly Java Driver(Type 2) Net-Protocol All-Java Driver (Type 3) Native Protocol All-Java Driver (Type 4)

Java.sun.com/products/jdbc/jdbcdrivers.html

JDBC ver 1.0

JDBC driver types JDBC drivers are divided into four types or levels. Each type defines a JDBC driver implementation with increasingly higher levels of platform independence, performance, and deployment administration. The four types are: Type 1: JDBC-ODBC Bridge driver Type 2: Native-API/partly Java driver Type 3: Net-protocol/all-Java driver Type 4: Native-protocol/all-Java driver

JDBC ver 1.0

Type 1: JDBC-ODBC Bridge The type 1 driver, JDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase Connectivity) calls and sends them to the ODBC driver. As such, the ODBC driver, as well as, in many cases, the client database code, must be present on the client machine. JDBC-ODBC Bridge environment.

JDBC ver 1.0

Advantages The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Type 1 drivers may be useful for those companies that have an ODBC driver already installed on client machines. DisAdvantages The performance is degraded since the JDBC call goes through the bridge to the ODBC driver, then to the native database connectivity interface. The result comes back through the reverse process. Therefore considering the performance issue, type 1 drivers may not be suitable for large-scale applications. The ODBC driver and native connectivity interface must already be installed on the client machine. Thus any advantage of using Java applets in an intranet environment is lost, since the deployment problems of traditional applications.
7 JDBC ver 1.0

Type 2: Native-API/partly Java driver JDBC driver type 2 -- the native-API/partly Java driver -- converts JDBC calls into database-specific calls for databases such as SQL Server, Informix, Oracle, or Sybase. The type 2 driver communicates directly with the database server; therefore it requires that some binary code be present on the client machine.

JDBC ver 1.0

Advantages Better performance than the JDBC-ODBC Bridge. Disadvantages The vendor database library needs to be loaded on each client machine. Consequently, type 2 drivers cannot be used for the Internet. Lower performance than type 3 and type 4 drivers.

JDBC ver 1.0

Type 3: Net-protocol/all-Java driver JDBC driver type 3 -- the net-protocol/all-Java driver -- follows a three-tiered approach whereby the JDBC database requests are passed through the network to the middle-tier server. The middle-tier server then translates the request (directly or indirectly) to the database-specific native-connectivity interface to further the request to the database server. If the middle-tier server is written in Java, it can use a type 1 or type 2 JDBC driver to do this..

10

JDBC ver 1.0

Advantages The net-protocol/all-Java driver is server-based, so there is no need for any vendor database library to be present on client machines. Further, there are many opportunities to optimize portability, performance, and scalability. Moreover, the net protocol can be designed to make the client JDBC driver very small and fast to load. Additionally, a type 3 driver typically provides support for features such as caching (connections,query results, and so on), load balancing, and advanced system administration such as logging and auditing DisAdvantages Type 3 drivers require database-specific coding to be done in the middle tier. Additionally, traversing the recordset may take longer, since the data comes through the backend server.

11

JDBC ver 1.0

Type 4: Native-protocol/all-Java driver The native-protocol/all-Java driver (JDBC driver type 4) converts JDBC calls into the vendor-specific database management system (DBMS) protocol so that client applications can communicate directly with the data base server. Level 4 drivers are completely implemented in Java to achieve platform independence and eliminate deployment administration issues.

Network

12

JDBC ver 1.0

Advantages Since type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good. The native -protocol/all-Java driver boasts better performance than types 1 and 2. Also, there's no need to install special software on the client or server. Further, these drivers can be downloaded dynamically. Disadvantages With type 4 drivers, the user needs a different driver for each database.

13

JDBC ver 1.0

Structured Query Language(SQL)


It is a fourth generation language It is a database language It has statements for data definition, query and Update (hence it is a DDL and a DML) Generally every database SQL language would have one 3rd generation language embedded to increase its problem solving efficiency

14

JDBC ver 1.0

JDBC Contd.
Jdbc allows the use of SQL statements to interact (create, query and update) with the database SQL and JAVA syntax necessary to use jdbc effectively

15

JDBC ver 1.0

Jdbc API (java.sql)


Interfaces : Driver Connection Statement CallableStatement PrepatedStatement ResultSet ResultSetMetaData DataBaseMetaData
16 JDBC ver 1.0

Jdbc API (Classes)


Date DriverManager DriverPropertyInfo Time TimeStamp Types EXCEPTIONS SQLException SQLWarning BatchUpdateException
17 JDBC ver 1.0

Class DriverManager
Class Using the command Name: DriverManager public void registerDriver(Driver) Class.forName(classname_driver), static void deregisterDriver(Driver) automatically loads and registers the methods Connection getConnection(String url) driver. Connection getConnection(String url, String user,String pwd) Driver getDriver() Drivers are also classes in java. Example: Enumeration getDrivers() sun.jdbc.odbc.JdbcOdbcDriver void setLogWriter(PrintWriter p) this driver is supplied by Sun itself PrintWriter getLogWriter()
18 JDBC ver 1.0

Interface Driver
interface Name: Driver public Connection connect (String,Properties) methods boolean acceptsURL(String) int getMajorVersion() int getMinorVersion() boolean jdbcCompliant() DriverPropertyInfo getPropertyInfo(String,Properties)

19

JDBC ver 1.0

Example
Register a jdbc driver you want to use. Use the getDrivers() method to retrieve a list of registered drivers. Obtain the driverInformation by querying each of the available drivers.

Eg: DriverInfo.java

20

JDBC ver 1.0

Connecting to a Database
Load the driver by specifying the driver as a string use the getConnection() method of the DriverManager class to connect to the database getConnection method takes a URL as a parameter URL (a String) specifies the type of protocol/subprotocol jdbc will use to connect to the database) returns a Connection object
21 JDBC ver 1.0

Usage of Classes
DriverManager

getConnection(String url)

Connection

22

JDBC ver 1.0

Database URL
Goals of this convention Naming should include connection information net protocol should have port number/ host name JDBC:ODBC bridge should use the simple protocol

23

JDBC ver 1.0

URL Syntax
URLs in the getConnection() method should have the format :

jdbc:<subprotocol name>:<sub name> subprotocol: the database connectivity mechanism

supported by the driver. javatmp is an odbc protocol to Connect using dbnet subname: specify network address of db server source name at port 1526 with hmant001 (URL for n/w address //Hostname:port/subname) Example: ordbc as connection name jdbc:odbc:javatmp jdbc:dbnet://HMANT001:1526/ordb
24 JDBC ver 1.0

Odbc Subprotocol
This subprotocol used for accessing ODBC data sources subprotocol jdbc:odbc:<data-source-name>: [;<attribute-name=attribute-value> ] example jdbc:odbc:javatmp jdbc:odbc:NorthWind;UID=kgh;pwd=foo
25 JDBC ver 1.0

Interface Connection
interface Name Connection public Stmt createStatement() methods Stmt createStatement(int, int) CallableStmt prepareCall(String sql) PreparedStmt prepareStatement(String sql) void rollback() void commit() boolean get/setAutoCommit(boolean) int get/setTransactionIsolation(int) DatabaseMetaData getMetaData() void close() void clearWarnings()
26 JDBC ver 1.0

Example
Create a odbc dsn for an access database Register and load the jdbc-odbc driver. Connect to the database using getConnection(data source url ); If there is an exception thrown during the connection display info and exit

Eg1: CheckConnect.java Eg2: ConnectType4.java


27 JDBC ver 1.0

Example
Register and load the jdbc-odbc driver. Connect to the database using getConnection(String, Properties); or getConnection(String,String,String) If there is an exception thrown during the connection display info and exit

Eg: CheckConnect2.java
28 JDBC ver 1.0

Example
Create new instance of jdbc-odbc driver. Connect to database using the connect(String, Properties) method in the driver class If there is an exception thrown during the connection display info and exit

Eg: CheckConnect3.java
29 JDBC ver 1.0

Interface DatabaseMetaData
interface DatabaseMetaData Name String getDatabaseProductName()
public String getDatabaseProductVersion() Method getDriverMajorVersion(); methods intgetMetaData() of Connection interface returns int getDriverMinorVersion(); handle String getDriverName() to DatabaseMetaData String getDriverVersion() String getNumericFunctions() More methods are avaialable String getSystemFunctions() in this interface. String getStringFunctions()
30 JDBC ver 1.0

Example
Load / Register the jdbc-odbc driver Connect to database Use getMetaData() to return a handle to DatabaseMetaData Display information about the Database

Eg: DatabaseInfo.java
31 JDBC ver 1.0

Review
DriverManager getConnection(String) Connection getMetaData() DatabaseMetaData
32 JDBC ver 1.0

Retrieving Data from a DB


To retrieve data one must use one of the following classes to query the database (after connection has been established) Statement PreparedStatement CallableStatement A Statement object is returned from the createStatement() method of Connection interface
JDBC ver 1.0

33

Interface Statement
interface Name Statement public ResultSet executeQuery(String) methods int executeUpdate(String); boolean execute(String) To see the information in rows sent void close() from the database, we need to use ResultSet getResultSet() Method the ResultSet interface methods increateStatement() of void clearWarnings() Connection interface returns

handle to Statement
34

JDBC ver 1.0

Interface ResultSet
interface Name ResultSet public int findColumn(String colname) methods boolean getBoolean(int)/(String) String argument implies a column name <datatype> get<datatye>(int)/(String) int argument implies a column position void close() (count is from 1 onwards) ResultSetMetaData getMetaData() To find out the number of columns boolean next() and column types we need to use the boolean previous() ResultSetMetaData interface boolean wasNull()
35 JDBC ver 1.0

interface ResultSetMetaData
interface Name ResultSetMetaData public int getColumnCount() methods int getColumnDisplaySize(int) String getColumnLabel(int) String getColumnName(int) int getColumnType(int) String getColumnTypeName(int) boolean isReadOnly(int) boolean isSearchable(int) boolean isWritable(int) String getTableName(int)
36 JDBC ver 1.0

Example
Load/register the jdbc-odbc driver Connect to database get a handle to a statement, and call executeQuery() in the statement get the count of columns from the MetaData information display the information rowwise (Note all info is being displayed as a String)

Eg: SQLQuery.java
37 JDBC ver 1.0

Review
DriverManager getConnection(String) Statement

Connection

createStatement() executeQuery(...) ResultSet getMetaData()


38 JDBC ver 1.0

ResultSetMetaData

Example
Load / Register the jdbc-odbc driver Connect to database Get a handle to a statement, and call executeQuery() in the statement Get the count of columns from the MetaData information Display the column information of table

Eg: SQLQueryTableInfo.java
39 JDBC ver 1.0

SQL Data Types & Java Data / Objects


CHAR String VARCHAR String LONGVARCHAR String NUMERIC java.math.BigDecimal DECIMAL java.math.BigDecimal BIT boolean SQL defines its data types. Hence int whileTINYINT java retrieves these data types, SMALLINT int one INTEGER must known the type conversion int between the two. long BIGINT
JDBC ver 1.0

40

SQL Data Types & Java Data / Objects


REAL FLOAT DOUBLE BINARY VARBINARY DATE TIME TIMESTAMP
41

float double double byte[ ] byte[ ] java.sql.Date java.sql.Time java.sql.Timestamp


JDBC ver 1.0

Data Conversion in ResultSets


getXXX(i) will attempt to convert the SQL Data type of column i into whatever type getXXX() method returns Example let the first column in the Result set be an ID number (SQL TYPE: INTEGER) if we use getString(1), it converts the INTEGER of SQL into a String object, and it returns a handle to this object Hence to return an integer, one must use getInt (1) which returns an int
42 JDBC ver 1.0

SQL NULL
To determine whether the SQL returned value is null
Step 1: read the value using getXXX(). Setup 2: use the wasNull() method of the Result set class. If it returns true the value just read was a SQL Null value it getXXX() would return zero for SQL nulls for int, byte, long
43 JDBC ver 1.0

Passing Parameters to SQL Statements


To retrieve a row based on a value, one cannot use the following query string select empid, name from employees where empid=3
the problem with the above statement is that the empid is having value string 3 and not int 3.

Solution: Use PrepareStatement instead of the Statement class


44 JDBC ver 1.0

Batch Updating
Step 1 : add the executable queries to statement - Statement. addBatch(SQL Query); Step 2 : execute Batch - int [] Statement.executeBatch(); Step 3 : Process the integer array.
Eg. : BatchUpdate.java
45 JDBC ver 1.0

Interface PreparedStatement
interface Name PreparedStatement public ResultSet executeQuery() methods int executeUpdate(); The string to be queried must be passed boolean execute(); to prepareStatement of Connection ResultSet getResultSet() class as a parameter. void clearParameters() setxxx() methods in this interface do not do void setXXX(int,XXX)

conversions, but insert the corresponding java to SQL mapped data types
46

JDBC ver 1.0

Setting Parameters in Query


To create a query In parameters in the query string are filled select empid, empname, empdesc from with ? marks. employees where empid=3

PreparedStatement set Use setXXX(1, val) tops = the first conn.prepareStatement(select parameter with val of type XXX empid,

empname, empdesc form employees Use setXXX(2, ) to insert at the second where empid=?); question mark ps.setInt(1,3); ps.executeQuery();
47 JDBC ver 1.0

Example
Load / Register the jdbc-odbc driver Connect to database Display information about the person with employeeID = 3 from employees table in Northwind database.

Eg: SQLQuery2.java
JDBC ver 1.0

48

Exercise
Create a table Projects with the following specifications ProjectID - integer SQLExercise.java ProjectName - text ProjectLocation - text ProjectStartDate - Date insert the values (1, ecom, hma, 1985-03-9) (2, corba, hst, 1945-06-26) (3, hxml, lst, 1996-09-5)
49 JDBC ver 1.0

Sending SQL Nulls as Parameters


To send an SQL null as parameter use the setNull(int,int) in the PreparedStatement interface first integer is the position of the parameter second integer is the constant for SQLtype of parameter constants defined in java.sql.Types.xxx java.sql.Types.VARCHAR java.sql.Types.BIT
50 JDBC ver 1.0

Exercise
Insert the value into the table Projects created in the previous exercise . (4, Cold Fusion, , 1999-09-9)

SQLExercise2.java

51

JDBC ver 1.0

Stored Procedures
To execute a stored procedure call, one must use the CallableStatement interface This can be created using the prepareCall(String) method of the Connection interface A stored procedure call might return some values to retrieve them, you need to register the out parameter types before executing the stored procedure query CallableStatement extends from PreparedStatement interface
52 JDBC ver 1.0

Illustration
CallableStatement stmt = conn.prepareCall({call getTestData(?,?) }); // getTestData has 2 OUT parameters stmt.registerOutParameter(1,Types.TINYINT); stmt.registerOutParameter(2,Types.DOUBLE); int i = stmt.executeUpdate(); byte x = stmt.getByte(1); double d = stmt.getDouble(2);
53 JDBC ver 1.0

DriverManager getConnection Connection


aa mt c etter tneSe t n e m a S r p

subclass Statement PreparedStatement CallableStatement executeQuery setXXX executeUpdate; getResultSet getXXX ResultSet
54 JDBC ver 1.0

ppea r aC er l

getXXX Data types: Date int, Time, long double, float

Creating a Stored Procedure


Steps to create a stored procedure in the database String createProcedure = "create procedure SHOWEMP " + "as " + "select * FROM emp; Statement stmt = conn.createStatement(); stmt.executeUpdate(createProcedure);

55

JDBC ver 1.0

Calling the Stored Procedure


Steps to execute a stored procedure in the database CallableStatement stmt = conn.prepareCall( { call SHOWEMP }); ResultSet rs = stmt.executeQuery();

56

JDBC ver 1.0

Exercise (contd)
19. The application, as of now, is having difficulty in managing the data stored in the files. Further, accessing, this data according to various permutations and combinations has been a tedious task. Therefore, it is suggested that the data in the files be migrated to a RDBMS

57

JDBC ver 1.0

Das könnte Ihnen auch gefallen