Presentation is loading. Please wait.

Presentation is loading. Please wait.

JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.

Similar presentations


Presentation on theme: "JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and."— Presentation transcript:

1 JDBC

2 Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and organizes data Stores and organizes data SQL SQL Relational database Relational database Structured Query Language Structured Query Language

3 Relational Database Relational database Relational database Table Table Rows, columns Rows, columns Primary key Primary key Unique data Unique data SQL statement SQL statement Query Query

4 SQL SQL overview SQL overview SQL keywords SQL keywords

5 SQL: SELECT QUERY Simplest form of a SELECT query Simplest form of a SELECT query SELECT * FROM tableName SELECT * FROM tableName SELECT * FROM authors SELECT * FROM authors Select specific fields from a table Select specific fields from a table SELECT authorID, lastName FROM authors SELECT authorID, lastName FROM authors

6 SQL: WHERE CLAUSE specify the selection criteria specify the selection criteria SELECT columnName1, columnName2, … FROM tableName WHERE criteria SELECT columnName1, columnName2, … FROM tableName WHERE criteria SELECT title, editionNumber, copyright SELECT title, editionNumber, copyright FROM titles WHERE copyright > 2000 WHERE clause condition operators WHERE clause condition operators, =, =, <>, =, =, <> LIKE LIKE wildcard characters % and _ wildcard characters % and _

7 SQL: ORDER BY Clause Optional ORDER BY clause Optional ORDER BY clause SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC SELECT columnName1, columnName2, … FROM tableName ORDER BY column ASC SELECT columnName1, columnName2, … FROM tableName ORDER BY column DESC SELECT columnName1, columnName2, … FROM tableName ORDER BY column DESC ORDER BY multiple fields ORDER BY multiple fields ORDER BY column1 sortingOrder, column2 sortingOrder, … ORDER BY column1 sortingOrder, column2 sortingOrder, … Combine the WHERE and ORDER BY clauses Combine the WHERE and ORDER BY clauses

8 SQL: INSERT Insert a row into a table Insert a row into a table INSERT INTO tableName ( columnName1, …, columnNameN ) INSERT INTO tableName ( columnName1, …, columnNameN ) VALUES ( value1, …, valueN ) VALUES ( value1, …, valueN ) INSERT INTO authors ( firstName, lastName ) INSERT INTO authors ( firstName, lastName ) VALUES ( ‘Sue’, ‘Smith’ ) VALUES ( ‘Sue’, ‘Smith’ )

9 SQL: UPDATE Modify data in a table Modify data in a table UPDATE tableName UPDATE tableName SET columnName1 = value1, …, columnNameN = valueN SET columnName1 = value1, …, columnNameN = valueN WHERE criteria WHERE criteria UPDATE authors UPDATE authors SET lastName = ‘Jones’ SET lastName = ‘Jones’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’ WHERE lastName = ‘Smith’ AND firstName = ‘Sue’

10 SQL: DELETE Remove data from a table Remove data from a table DELETE FROM tableName WHERE criteria DELETE FROM tableName WHERE criteria DELETE FROM authors DELETE FROM authors WHERE lastName = ‘Jones’ AND firstName = ‘Sue’ WHERE lastName = ‘Jones’ AND firstName = ‘Sue’

11 Layers of a DB Application A database application consists of three layers A database application consists of three layers Database Management System Database Management System Application logic (business rules) Application logic (business rules) Presentation logic (interface) Presentation logic (interface)

12 Java DB Support JDBC JDBC Java Data Base Connectivity Java Data Base Connectivity A set of interfaces to provide consistent API for accessing databases from different vendors A set of interfaces to provide consistent API for accessing databases from different vendors Vendors must provide the implementation of these interfaces in order to facilitate a java application to access their database Vendors must provide the implementation of these interfaces in order to facilitate a java application to access their database

13 JDBC Implemented in java.sql package Implemented in java.sql package Provides set of interfaces to allow access to third party databases Provides set of interfaces to allow access to third party databases Platform independent Platform independent Changes underlying db doesn’t cause significant change in the application Changes underlying db doesn’t cause significant change in the application Also allows access to vendor-specific features Also allows access to vendor-specific features

14 JDBC Driver JDBC Driver: JDBC Driver: set of classes that interface with a specific database engine. set of classes that interface with a specific database engine. JDBC drivers exist for every major database including: Oracle, SQL Server, Sybase, and MySQL. JDBC drivers exist for every major database including: Oracle, SQL Server, Sybase, and MySQL.

15 JDBC Driver Java Application JDBC Driver Manager JDBC- ODBC Bridge Vendor Specific JDBC Driver Vendor Specific JDBC Driver Database

16 Database Drivers Type 1 - Bridge Drivers Type 1 - Bridge Drivers Drivers in Java code which connect a Java client to a non-java database service (such as ODBC). Drivers in Java code which connect a Java client to a non-java database service (such as ODBC). Type 2 - Part-Java Drivers (Native) Type 2 - Part-Java Drivers (Native) Wraps (possibly existing) native code libraries with Java code to implement JDBC. Wraps (possibly existing) native code libraries with Java code to implement JDBC. Type 3 - Network All-Java Drivers (Middleware) Type 3 - Network All-Java Drivers (Middleware) All java code which connects to middleware to access a database via a network protocol. This type of driver may be used with applets or servlets. All java code which connects to middleware to access a database via a network protocol. This type of driver may be used with applets or servlets. Type 4 - Direct All-Java Drivers (Pure) Type 4 - Direct All-Java Drivers (Pure) This provides a pure Java JDBC implementation which can be accessed directly and possibly provide services to networking middleware. This provides a pure Java JDBC implementation which can be accessed directly and possibly provide services to networking middleware.

17 JDBC Drivers (Fig.) JDBC Type I “Bridge” Type II “Native” Type III “Middleware” Type IV “Pure” ODBC Driver CLI (.lib) Middleware Server

18 JDBC Application Architecture ApplicationJDBCDriver Java code calls JDBC library Java code calls JDBC library JDBC loads a driver JDBC loads a driver Driver talks to a particular database Driver talks to a particular database Can have more than one driver -> more than one database Can have more than one driver -> more than one database Ideal: can change database engines without changing any application code Ideal: can change database engines without changing any application code

19 JDBC Interfaces CallableStatement CallableStatement Connection Connection DatabaseMetaData DatabaseMetaData Driver Driver PreparedStatement PreparedStatement ResultSet ResultSet ResultSetMetaData ResultSetMetaData Statement Statement

20 JDBC Classes Date Date DriverManager DriverManager DriverPropertyInfo DriverPropertyInfo Time Time Timestamp Timestamp Types Types

21 JDBC Six step Procedure Six step Procedure Load the JDBC Driver Load the JDBC Driver Establish the Database Connection Establish the Database Connection Create a Statement Object Create a Statement Object Execute a Query Execute a Query Process the Results Process the Results Close the Connection Close the Connection

22 JDBC CLASS USAGE DriverManager Driver Connection Statement ResultSet

23 JDBC: Loading the Driver A simple reference to the driver loads it into the JVM A simple reference to the driver loads it into the JVM Class.forName(name_of_the_driver) Class.forName(name_of_the_driver) Driver name is a string representing the complete hierarchy of the driver class i.e. the package and class name Driver name is a string representing the complete hierarchy of the driver class i.e. the package and class name For a JDBC-ODBC Driver For a JDBC-ODBC Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriv er");

24 Establish the Connection Static method getConnection of Class Driver Manager returns a Connection object. Static method getConnection of Class Driver Manager returns a Connection object. Can throw SQLException Can throw SQLException Connection con = DriverManager.getConnection(url, user, password ) Connection con = DriverManager.getConnection(url, user, password )

25 Connection URL The only difficulty in establishing a connection is specifying the correct URL. The only difficulty in establishing a connection is specifying the correct URL. General format of connection URL is jdbc:subprotocol:subname. General format of connection URL is jdbc:subprotocol:subname. JDBC indicates that this is a JDBC Connection. JDBC indicates that this is a JDBC Connection. The subprotocol identifies the driver to be used The subprotocol identifies the driver to be used The subname identifies the database name/location. The subname identifies the database name/location.

26 Connection URL For example, the following code uses a JDBC-ODBC bridge to connect to the local database db: For example, the following code uses a JDBC-ODBC bridge to connect to the local database db: String url = "jdbc:odbc:db"; Connection con = DriverManager.getConnection(url, "cerami", "password");

27 Create a Statement Object The JDBC Statement object sends SQL statements to the database. The JDBC Statement object sends SQL statements to the database. Statement objects are created from active Connection objects. Statement objects are created from active Connection objects. For example: For example: Statement stat = con.createStatement(); Statement stat = con.createStatement(); SQL calls can then be made on the database through statement object SQL calls can then be made on the database through statement object

28 Execute a Query executeQuery(String query) executeQuery(String query) Executes a select query on the database and returns the selected data in the form of a ResultSet object Executes a select query on the database and returns the selected data in the form of a ResultSet object The returned ResultSet object may be empty but cannot be null The returned ResultSet object may be empty but cannot be null Throws SQLException Throws SQLException ResultSet rs = stat.executeQuery (“Select * from table”); ResultSet rs = stat.executeQuery (“Select * from table”);

29 Execute Query executeUpdate(String query) executeUpdate(String query) Executes INSER, UPDATE, DELETE SQL statements Executes INSER, UPDATE, DELETE SQL statements Returns an integer value representing the number of rows affected by this operation Returns an integer value representing the number of rows affected by this operation Throws SQLException Throws SQLException Also supports DDL statements CREATE TABLE, DROP TABLE, ALTER TABLE Also supports DDL statements CREATE TABLE, DROP TABLE, ALTER TABLE int rows = executeUpdate(“delete * from table”); int rows = executeUpdate(“delete * from table”);

30 Process the Result A ResultSet contains the results of the SQL query A ResultSet contains the results of the SQL query ResultSet Methods ResultSet Methods All methods can throw a SQLException All methods can throw a SQLException Close() Close() Releases the JDBC and database resources Releases the JDBC and database resources A ResultSet object is automatically closed when its associated statement object runs a new query. A ResultSet object is automatically closed when its associated statement object runs a new query. getMetaData() getMetaData() Returns ResultSetMetaData object Returns ResultSetMetaData object This object contains information about the columns in the ResultSet. This object contains information about the columns in the ResultSet.

31 ResultSet next() next() Attempts to move to the next row of data in the ResultSet Attempts to move to the next row of data in the ResultSet Returns true if successful and Returns true if successful and False otherwise False otherwise First call to the next() method positions the cursor at the first data row First call to the next() method positions the cursor at the first data row

32 ResultSet findColumn(String) findColumn(String) Maps a ResultSet column name to a ResultSet column index Maps a ResultSet column name to a ResultSet column index Returns an integer value that corresponds to the specified column name Returns an integer value that corresponds to the specified column name

33 ResultSet getXXX(String), getXXX(int) getXXX(String), getXXX(int) Returns the value from the column specified by column name (String version) or column index (int) as an XXX Java type Returns the value from the column specified by column name (String version) or column index (int) as an XXX Java type First column index is 1 not 0 First column index is 1 not 0 Returns 0 or null, if the value is a SQL NULL Returns 0 or null, if the value is a SQL NULL Can call wasNull(). Can call wasNull(). Legal getXxx types Legal getXxx types doublebyteint Date Stringfloat short long Time Object

34 Close the Connection To close the database connection To close the database connection stat.close(); stat.close(); con.close() con.close()

35 Mapping SQL Types To JAVA SQL type Java Type SQL type Java Type CHAR, VARCHAR, LONGVARCHARString CHAR, VARCHAR, LONGVARCHARString NUMERIC, DECIMALjava.math.BigDecimal NUMERIC, DECIMALjava.math.BigDecimal BITboolean BITboolean TINYINTbyte TINYINTbyte SMALLINTshort SMALLINTshort INTEGERint INTEGERint BIGINTlong BIGINTlong REALfloat REALfloat FLOAT, DOUBLEdouble FLOAT, DOUBLEdouble BINARY, VARBINARY, LONGVARBINARYbyte[] BINARY, VARBINARY, LONGVARBINARYbyte[] DATEjava.sql.Date DATEjava.sql.Date TIMEjava.sql.Time TIMEjava.sql.Time TIMESTAMPjava.sql.Timestamp TIMESTAMPjava.sql.Timestamp

36 Transaction Management Transactions are not explicitly opened and closed Transactions are not explicitly opened and closed Instead, the connection has a state called AutoCommit mode Instead, the connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed if AutoCommit is true, then every statement is automatically committed default case: true default case: true

37 Transaction Management Connection.setAutoCommit(boolean) if AutoCommit is false, then every statement is added to an ongoing transaction if AutoCommit is false, then every statement is added to an ongoing transaction you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback() you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()

38 JDBC Class Diagram

39 Stored Procedures Stored procedures Stored procedures Store SQL statements in a database Store SQL statements in a database Invoke SQL statements by programs accessing the database Invoke SQL statements by programs accessing the database Interface CallableStatement Interface CallableStatement Receive arguments Receive arguments Output parameters Output parameters

40 Meta Data Database/Connection Database/Connection DatabaseMetaData: getMetaData(); DatabaseMetaData: getMetaData(); ResultSet ResultSet ResultSetMetaData: getMetaData() ResultSetMetaData: getMetaData()

41 Resultset Metadata What's the number of columns in the ResultSet? What's the number of columns in the ResultSet? What's a column's name? What's a column's name? What's a column's SQL type? What's a column's SQL type? What's the column's normal max width in chars? What's the column's normal max width in chars? What's the suggested column title for use in printouts and displays? What's the suggested column title for use in printouts and displays? What's a column's number of decimal digits? What's a column's number of decimal digits? Does a column's case matter? Does a column's case matter? Will a write on the column definitely succeed? Will a write on the column definitely succeed? Can you put a NULL in this column? Can you put a NULL in this column? Is a column definitely not writable? Is a column definitely not writable? Can the column be used in a where clause? Can the column be used in a where clause? Is the column a signed number? Is the column a signed number? Is it possible for a write on the column to succeed? Is it possible for a write on the column to succeed? and so on... and so on...

42 Database Metadata What tables are available? What tables are available? What's our user name as known to the database? What's our user name as known to the database? Is the database in read-only mode? Is the database in read-only mode?


Download ppt "JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and."

Similar presentations


Ads by Google