83
© People Strategists - Duplication is strictly prohibited - www.peoplestrategists.com

JDBC

Embed Size (px)

Citation preview

© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com

© People Strategists - Duplication is strictly prohibited -www.peoplestrategists.com

Java Database Connectivity (JDBC)

JDBC Overview

• JDBC is an Application Programming Interface (API) that allows a Java programmer to access any kind of tabular data, such as a database in a Java application.

• JDBC allows the programmers to develop Java applications that can:• Connect to a data source, such as a database

• Send queries and update statements to the database

• Retrieve and process the results received from the database

JDBC Overview (Contd.)

• JDBC enables programmers to develop data-centric applications that can access and manipulate data from diverse range of databases.

• For this, JDBC API consists of different types of JDBC drivers, as shown in the following figure.

Types of Drivers

• A JDBC driver is a collection of Java classes that enables a programmer to connect a Java application to a certain database.

• There are four types of JDBC drivers to connect with different types of databases. These are:• Type 1: JDBC-ODBC Bridge Driver

• Type 2: JDBC-Native API Driver

• Type 3: JDBC-Net Pure Java Driver

• Type 4: Thin driver

Types of Drivers (Contd.)

• Type 1: JDBC-ODBC Bridge Driver:• While using type 1 driver, a JDBC bridge is used to access ODBC drivers

installed on each client machine. • To enable this driver to use ODBC, you need to configure a Data Source Name

(DSN) that represents the target database on your system. • This driver converts JDBC method calls into the ODBC function calls to enable

interactions with the database.• This driver is easy to use and can be easily connected to any database.• However, it decreases the performance of the application, as JDBC method

calls need to be converted into the ODBC function.• Use of type 1 drivers requires installation of ODBC driver on the client

machine.

Types of Drivers (Contd.)

• Type 1: JDBC-ODBC Bridge Driver:• The following figure shows the diagrammatic representation of Type 1 driver

use.

Types of Drivers (Contd.)

• Type 2: JDBC-Native API Driver:• While using Type 2 driver, JDBC API calls are converted into native C/C++ API

calls, which are unique to the database.

• These drivers are typically provided by the database vendors and used in the same manner as the JDBC-ODBC Bridge.

• The vendor-specific driver must be installed on each client machine.

• Therefore, when the database is changed, the database specific native API needs to be installed.

• Use of the type 2 driver improves the application performance as compared to the type 1 driver.

Types of Drivers (Contd.)

• Type 2: JDBC-Native API Driver:• The following figure shows the diagrammatic representation of Type 2 driver

use.

Types of Drivers (Contd.)

• Type 3: JDBC-Net Pure Java Driver:• While using Type 3 driver, a three-tier approach is used to access databases,

as shown in the following figure.

Types of Drivers (Contd.)

• Type 3: JDBC-Net Pure Java Driver:• This driver uses middleware (application server) that converts JDBC calls

directly or indirectly into the vendor-specific database protocol.

• The JDBC clients use standard network sockets to communicate with a middleware application server.

• The socket information is then translated by the middleware application server into the call format required by the DBMS, and forwarded to the database server.

• Use of type 3 driver is extremely flexible as it does not require you to install any vendor specific code on the client and a single driver can provide access to multiple databases.

Types of Drivers (Contd.)

• Type 4: Thin driver:• While using type 4 driver, the JDBC calls are directly converted into the

vendor-specific database protocol.

• Type 4 driver communicates directly with the vendor's database through socket connection.

• This is the highest performance driver available for the database and is usually provided by the vendor itself.

• Type 4 driver is the highly flexible and also referred to as thin driver.

java.sql Interfaces Driver, Connection, Statement• The core components of JDBC are provided under the java.sql

package.

• These core components includes, but are not limited to:• JDBC Drivers: Allow establishing a communication between a database and a

Java application. It is available as Driver interface in the java.sqlpackage.

• Connections: Allow establishing a connection session with the database. It is available as the Connection interface in the java.sql package.

• Statements: Allow executing static SQL statements and returning the results. It is available as the Statement interface in the java.sql package. To execute dynamic SQL statements the PreparedStatement interface is available in java.sql package.

java.sql Interfaces Driver, Connection, Statement (Contd.)

• Result Sets: Allow storing the data retrieved as a result of a SQL queries in a tabular format. It is available as the Statement interface in the java.sqlpackage.

• Database Meta Data : Allow to get comprehensive information about the database as a whole. It is available as DatabaseMetaData interface in java.sql package.

• Result Set Meta Data: Allows to get information about the types and properties of the columns in the ResultSet object. It is available as the ResultSetMetaData interface in the java.sql package.

• The preceding JDBC core components help a programmer to establish a connection with a database and manipulate the required data.

java.sql Interfaces Driver, Connection, Statement (Contd.)• To perform different operations on data in a database by using JDBC,

a programmer needs to perform the following steps in an application:• Import the packages for JDBC

• Register the JDBC driver for the corresponding database

• Create database URL

• Create connection to the database

• Interact with the database

java.sql Interfaces Driver, Connection, Statement (Contd.)• Example:

import java.sql.*; //Import statement for JDBC

public class JDBCTest {

public static void main(String[] args)throws

SQLException, ClassNotFoundException {

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

java.sql Interfaces Driver, Connection, Statement (Contd.)try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL,

userName, password);

Statement stmt = conn.createStatement();

ResultSet results = stmt.executeQuery("select * from

city");

java.sql Interfaces Driver, Connection, Statement (Contd.)

System.out.println("\n-------------------------------

-------------------------------------");

while(results.next()){

int id = results.getInt(1);

String name = results.getString(2);

String cc = results.getString(3);

String dist = results.getString(4);

int pop = results.getInt(5);

System.out.println(id + "\t" + name + "\t" + cc+

"\t" + dist+ "\t" + pop);

}

java.sql Interfaces Driver, Connection, Statement (Contd.)

//Closing resultset, statement, and connection

results.close();

stmt.close();

conn.close();

}

catch(Exception e){

System.out.println(e);

}

}

}

java.sql Interfaces Driver, Connection, Statement (Contd.)

• Output:

Loading a Driver and Establishing a Connection Using DriverManager• In the preceding example, the static method, forName() of the Class class is used to load the database driver.

• An alternative approach to load the database driver is by using the registerDriver() static method of the DriverManagerclass.

• For this, first you need to create an instance of the Driver class.

• Further, you can use the getConnection() static method of the DriverManager class to establish a connection with the database.

Loading a Driver and Establishing a Connection Using DriverManager (Contd.)• Example:

//Registering JDBC driver

Driver myDriver=new

org.apache.derby.jdbc.ClientDriver();

DriverManager.registerDriver(myDriver);

//Creating database URL

String dbURL = "jdbc:derby://localhost:1527/

University;create=true;user=uni;password=uni@123";

//Creating connection to the database

Connection conn=DriverManager.getConnection(dbURL);

Perform CRUD Operations Using JDBC Interfaces• The JDBC API provides you with the interfaces that defines the

methods to perform Create, Read, Update, and Delete (CRUD) operations on the database.

• One of these interfaces is the Statement interface, which defines most of the methods required to perform CRUD operations.

• The commonly used methods of the Statement interface that help performing CRUD operations are:• boolean execute(String sql)

• ResultSet executeQuery(String sql)

• int executeUpdate(String sql)

Perform CRUD Operations Using JDBC Interfaces (Contd.)• boolean execute(String sql)

• Executes the given SQL statement, which may return multiple results.

• Is used in the situations where you are not sure whether the query to be executed is an insert, update, or delete statement or it is a query to retrieve data.

• ResultSet executeQuery(String sql)

• Executes the given SQL statement, which returns a single ResultSetobject.

• Is used to execute the queries that retrieve data from the databse.

Perform CRUD Operations Using JDBC Interfaces (Contd.)• int executeUpdate(String sql)

• Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

• These methods can be used for different types of database interactions, such as:• Create a table• Insert records• Select records• Update records• Delete records• Drop a table

Perform CRUD Operations Using JDBC Interfaces (Contd.)• Creating a Table:

• To create a table by using JDBC, you need to execute CREATE TABLE query by using the executeUpdate()method, as shown in the following code snippet:

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

Perform CRUD Operations Using JDBC Interfaces (Contd.)try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL, userName, password);

String qry = "CREATE TABLE REGISTRATION " +

"(id INTEGER not NULL, " +

" Name VARCHAR(25), " +

" Address VARCHAR(255), " +

" Email_ID VARCHAR(50), " +

" Phone VARCHAR(50)," +

" PRIMARY KEY ( id ))";

Perform CRUD Operations Using JDBC Interfaces (Contd.)

stmt.executeUpdate(qry);

stmt.close();

conn.close();

}catch(Exception e){

e.printStackTrace();

}

Perform CRUD Operations Using JDBC Interfaces (Contd.)• Inserting Records:

• To insert records into a table by using JDBC, you need to execute the INSERT query by using the executeUpdate() method, as shown in the following code snippet:

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

Perform CRUD Operations Using JDBC Interfaces (Contd.)try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL, userName, password); Statement stmt = conn.createStatement();

String qry = "INSERT INTO Registration " +

"VALUES (101, 'Manish', 'F-130, New Delhi', '[email protected]', '91+8976546575')";

Perform CRUD Operations Using JDBC Interfaces (Contd.)

stmt.executeUpdate(qry);

stmt.close();

conn.close();

}catch(Exception e){

e.printStackTrace();

}

Perform CRUD Operations Using JDBC Interfaces (Contd.)• Selecting Records:

• To select records from a table by using JDBC, you need to execute the SELECT query by using the executeQuery() method, as shown in the following code snippet:

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

Perform CRUD Operations Using JDBC Interfaces (Contd.)try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL,

userName, password);

Statement stmt = conn.createStatement();

String qry = "SELECT * FROM Registration";

ResultSet results = stmt.executeQuery(qry);

Perform CRUD Operations Using JDBC Interfaces (Contd.)

while(results.next()){

int id = results.getInt(1);

String sName = results.getString(2);

String sAddress = results.getString(3);

String sEmail = results.getString(4);

String sPhone = results.getString(5);

System.out.println(id + "\t" + sName + "\t" +

sAddress+ "\t" + sEmail+ "\t" + sPhone);

}

Perform CRUD Operations Using JDBC Interfaces (Contd.)

stmt.close();

conn.close();

}catch(Exception e){

e.printStackTrace();

}

• Output:

Perform CRUD Operations Using JDBC Interfaces (Contd.)• You can obtain meta data information about the database and table

using the DatabaseMetaData and ResultSetMetaData interfaces.

• Some of the commonly used methods of DatabaseMetaData interface are:• getURL(): Returns the URL for the DBMS• getSQLKeywords(): Retrieves a comma-separated list of all of this database's

SQL keywords that are NOT also SQL92 keywords. • supportsTransactions(): Retrieves whether this database supports

transactions. If not, invoking the method commit is no use, and the isolation level is TRANSACTION_NONE.

• supportsSelectForUpdate(): Retrieves whether this database supports SELECT FOR UPDATE statements.

Perform CRUD Operations Using JDBC Interfaces (Contd.)• Some of the commonly used methods of ResultSetMetaData are:

• getColumnCount(): Returns the number of columns in the result set object.

• getColumnName():Returns the column names in the result set object.• getColumnTypeName(): Returns the data type of the columns in the

result set object.

• Example:import java.sql.*; //Import statement for JDBC

public class JDBCTest {

public static void main(String[] args)throws SQLException, ClassNotFoundException {

Perform CRUD Operations Using JDBC Interfaces (Contd.)

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL, userName,

password);

//Starting database interaction

Statement stmt = conn.createStatement();

DatabaseMetaData dbmd = conn.getMetaData();

Perform CRUD Operations Using JDBC Interfaces (Contd.)

System.out.println(dbmd.getURL());

System.out.println(dbmd.getSQLKeywords());

System.out.println(dbmd.supportsTransactions());

System.out.println(dbmd.supportsSelectForUpdate());

ResultSet results = stmt.executeQuery("select * from country");

ResultSetMetaData rsmd = results.getMetaData();

for (int i = 1; i <= rsmd.getColumnCount(); i++) {

String colName = rsmd.getColumnName(i);

String colType = rsmd.getColumnTypeName(i);

System.out.println(colName+"\t"+colType);

}

Perform CRUD Operations Using JDBC Interfaces (Contd.)

//Closing resultset, statement, and connection

results.close();

stmt.close();

conn.close();

}

catch(Exception e){

System.out.println(e);

}

}

}

Perform CRUD Operations Using JDBC Interfaces (Contd.)• Output:

Perform CRUD Operations Using JDBC Interfaces (Contd.)• Updating Records:

• To updates records in a table by using JDBC, you need to execute the UPDATE query by using the executeUpdate() method, as shown in the following code snippet:

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

Perform CRUD Operations Using JDBC Interfaces (Contd.)try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL,

userName, password);

Statement stmt = conn.createStatement();

String qry = "UPDATE Registration " +"SET Address

= 'E-985, New Delhi' WHERE id = 101";

Perform CRUD Operations Using JDBC Interfaces (Contd.)

stmt.executeUpdate(qry);

qry = "SELECT * FROM Registration";

ResultSet results = stmt.executeQuery(qry);

while(results.next()){

int id = results.getInt(1);

String sName = results.getString(2);

String sAddress = results.getString(3);

String sEmail = results.getString(4);

String sPhone = results.getString(5);

System.out.println(id + "\t" + sName + "\t" + sAddress+ "\t" + sEmail+ "\t" + sPhone);

}

Perform CRUD Operations Using JDBC Interfaces (Contd.)

stmt.close();

conn.close();

}catch(Exception e){

e.printStackTrace();

}

• Output:

Perform CRUD Operations Using JDBC Interfaces (Contd.)• Deleting Records:

• To delete records from a table by using JDBC, you need to execute the DELETE query by using the executeUpdate() method, as shown in the following code snippet:

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

Perform CRUD Operations Using JDBC Interfaces (Contd.)try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL,

userName, password); Statement stmt =

conn.createStatement();

String qry = "DELETE FROM Registration WHERE

id = 101";

Perform CRUD Operations Using JDBC Interfaces (Contd.)

stmt.executeUpdate(qry);

stmt.close();

conn.close();

}catch(Exception e){

e.printStackTrace();

}

Perform CRUD Operations Using JDBC Interfaces (Contd.)• Dropping a Table:

• To drop a table by using JDBC, you need to execute the DROP query by using the executeUpdate()method, as shown in the following code snippet:

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

Perform CRUD Operations Using JDBC Interfaces (Contd.)

try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL, userName, password); Statement stmt = conn.createStatement();

String qry = "DROP TABLE REGISTRATION ";

stmt.executeUpdate(qry);

stmt.close();

conn.close();

}catch(Exception e){

e.printStackTrace();

}

Prepared Statement for Precompiled Queries

• While using JDBC for database interactions, you need to supply values in the queries while writing code using the instance of the Statement interface.

• However, if you want to supply the values to the precompiled queries at the run time, you cannot use the instance of the Statementinterface.

• For this, you need to use the instance of the of the PreparedStatement interface.

Prepared Statement for Precompiled Queries (Contd.)• The use of the PreparedStatement interface improves

application performance as queries are complied only once.

• To create an instance of the PreparedStatement interface, you need to use the prepareStatement() method of the Connectioninterface, as shown in the following code snippet: PreparedStatement updateemp = con.prepareStatement

("insert into emp values(?,?,?)");

• In the preceding code snippet, con is an instance of the Connectioninterface and ? is the placeholders for which values will be supplied at runtime.

Prepared Statement for Precompiled Queries (Contd.)• To set the values of the placeholders and execute queries, the PreparedStatement interface defines various methods, such as:• public void setInt(int paramIndex, int value)

• public void setString(int paramIndex, String value)

• public void setFloat(int paramIndex, float value)

• public void setDouble(int paramIndex, double value)

• public int executeUpdate()

• public ResultSet executeQuery()

Prepared Statement for Precompiled Queries (Contd.)• Example:

import java.sql.*;

public class PreparedStatementTest {

public static void main(String[] args) {

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL, userName, password); PreparedStatement insertEMP = conn.prepareStatement("insert into REGISTRATION values(?,?,?,?,?)");

Prepared Statement for Precompiled Queries (Contd.)

insertEMP.setInt(1, 102);

insertEMP.setString(2, "Dinesh");

insertEMP.setString(3, "M-260, Navi Mumbai");

insertEMP.setString(4, "[email protected]");

insertEMP.setString(5, "91+2045678909");

insertEMP.executeUpdate();

Statement stmt = conn.createStatement();

String qry = "SELECT * FROM Registration";

ResultSet results = stmt.executeQuery(qry);

Prepared Statement for Precompiled Queries (Contd.)

while(results.next()){

int id = results.getInt(1);

String sName = results.getString(2);

String sAddress = results.getString(3);

String sEmail = results.getString(4);

String sPhone = results.getString(5);

System.out.println(id + "\t" + sName + "\t" +

sAddress+ "\t" + sEmail+ "\t" + sPhone);

}

Prepared Statement for Precompiled Queries (Contd.)

insertEMP.close();

stmt.close();

conn.close();

}catch(Exception e){

e.printStackTrace();

}

}

}

Prepared Statement for Precompiled Queries (Contd.)• Output:

Callable Statement for Stored Procedures

• Similar to preapred statements, the callable statements are used to execute the precompiled queries, which are calls to procedures.

• To use callable statements in your application, you need to create an instance of the CallableStatement interface.

• This interface defines various methods to set the values at runtime similar to that of the PreparedStatment interface.

• To create an instance of the CallableStatement interface, you need to invoke the prepareCall() method of the Connectioninterface.

Callable Statement for Stored Procedures (Contd.)• Consider an example where you have created a procedure that

updates the employee name in a table. The procedure accepts the ID and name of an employee and returns the number of rows affected as an integer value.

• To call this procedure by using callable statement, you can use the following code snippet:

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

Callable Statement for Stored Procedures (Contd.)try{

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn =

DriverManager.getConnection(URL, userName,

password);

int iParam1 = 102;

Callable Statement for Stored Procedures (Contd.)

String iParam2 = "Raghav";

String proc = "{call UpdateEMP(?, ?, ?)}";

CallableStatement cs = conn.prepareCall(proc);

cs.setInt(1, iParam1);

cs.setString(2, iParam2);

cs.registerOutParameter(3, java.sql.Types.INTEGER);

cs.executeUpdate();

int oParam = cs.getInt(3);

System.out.println("Updated row count from the proc: " + oParam);

}catch(Exception E){

E.printStackTrace();

}

Transactions with JDBC

• The database transactions are managed by using the Connection object.

• The default mode of connection object is autocommit.

• The autocommit mode allows the statements to be executed and committed as individual transactions.

• You can change the autocommit mode by using setAutoCommit() method.

• To control transactions when autocommit mode is false the following methods are used:• commit():• rollback():

Transactions with JDBC

• The commit() method makes permanent all changes since the previous commit or rollback and releases any database locks held by the connection.

• The rollback() method drops all changes since the previous commit or rollback and releases any database locks.

• Example:import java.sql.*;

public class JDBCTest {

public static void main(String[] args)throws

SQLException, ClassNotFoundException {

Transactions with JDBC (Contd.)

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

try{

Class.forName(driverClass);

Connection conn = DriverManager.getConnection(URL, userName, password);

Statement stmt = conn.createStatement();

conn.setAutoCommit(false);

Transactions with JDBC (Contd.)

stmt.executeUpdate("create table Employee(empno integer,enamevarchar(20),deptno integer)");

stmt.executeUpdate("insert into Employee values(1,'sakre',1)");

stmt.executeUpdate("insert into Employee values(22,'pradeep',1)");

stmt.executeUpdate(" insert into Employee values (37,'vivek',5)");

conn.commit();

stmt.close();

conn.close();

}

catch(Exception e){

System.out.println(e);

}

}

}

Transactions with JDBC (Contd.)

• The preceding code will create a table named employee and insert values inside the table.

Mapping SQL and Java Types

• JDBC defines a standard mapping from the JDBC database types to Java types.

• For example, a JDBC INTEGER is normally mapped to a Java int.

• The different types of JDBC data types and their equivalent to standard SQL types and to Java types are:• CHAR: The SQL CHAR type corresponding to JDBC CHAR is defined in SQL-92

and is supported by all the major databases. It takes a parameter that specifies the string length. Thus CHAR(12) defines a 12-character string. All the major databases support CHAR lengths up to at least 254 characters.

Mapping SQL and Java Types (Contd.)

• VARCHAR: The SQL VARCHAR type corresponding to JDBC VARCHAR is defined in SQL-92 and is supported by all the major databases. It takes a parameter that specifies the maximum length of the string. Thus VARCHAR(12) defines a string whose length may be up to 12 characters. All the major databases support VARCHAR lengths up to 254 characters. When a string value is assigned to a VARCHAR variable, the database remembers the length of the assigned string and on a SELECT, it will return the exact original string.

• Java programmers do not need to distinguish among the three types of JDBC strings, CHAR, VARCHAR, and LONGVARCHAR. Each can be expressed as a Java String, and it is possible to read and write an SQL statement correctly without knowing the exact data type that was expected.

Mapping SQL and Java Types (Contd.)

• BINARY: The SQL BINARY type corresponding to JDBC BINARY is a non-standard SQL extension and is only implemented on some databases. It takes a parameter that specifies the number of binary bytes. Thus BINARY(12) defines a 12-byte binary type. Typically, BINARY values are limited to 254 bytes.

• VARBINARY: The SQL VARBINARY type corresponding to JDBC VARBINARY is a non-standard SQL extension and is only implemented on some databases. It takes a parameter that specifies the maximum number of binary bytes. Thus VARBINARY(12) defines a binary type whose length may be up to 12 bytes. Typically, VARBINARY values are limited to 254 bytes. When a binary value is assigned to a VARBINARY variable, the database remembers the length of the assigned value and on a SELECT, it will return the exact original value.

Mapping SQL and Java Types (Contd.)

• BINARY, VARBINARY, and LONGVARBINARY can all be expressed identically as byte arrays in Java. Since it is possible to read and write SQL statements correctly without knowing the exact BINARY data type that was expected, there is no need for Java programmers to distinguish among them.

• TINYINT:• The JDBC type TINYINT represents an 8-bit unsigned integer value between 0 and 255.

• The corresponding SQL type, TINYINT, is currently supported by only a subset of the major databases.

• The recommended Java mapping for the JDBC TINYINT type is as either a Java byte or a Java short. The 8-bit Java byte type represents a signed value from -128 to 127, so it may not always be appropriate for larger TINYINT values, whereas the 16-bit Java short will always be able to hold all TINYINT values.

Mapping SQL and Java Types (Contd.)

• SMALLINT:• The JDBC type SMALLINT represents a 16-bit signed integer value between -32768 and

32767.• The corresponding SQL type, SMALLINT, is defined in SQL-92 and is supported by all the

major databases. The SQL-92 standard leaves the precision of SMALLINT up to the implementation, but in practice, all the major databases support at least 16 bits.

• The recommended Java mapping for the JDBC SMALLINT type is as a Java short.

• INTEGER:• The JDBC type INTEGER represents a 32-bit signed integer value between - 2147483648

and 2147483647.• The corresponding SQL type, INTEGER, is defined in SQL-92 and is widely supported by all

the major databases. The SQL-92 standard leaves the precision of INTEGER up to the implementation, but in practice all the major databases support at least 32 bits.

• The recommended Java mapping for the INTEGER type is as a Java int.

Mapping SQL and Java Types (Contd.)

• BIGINT:• The JDBC type BIGINT represents a 64-bit signed integer value

between -9223372036854775808 and 9223372036854775807.

• The corresponding SQL type BIGINT is a non-standard extension to SQL. In practice the SQL BIGINT type is not yet currently implemented by any of the major databases, and we recommend that its use should be avoided in portable code.

• The recommended Java mapping for the BIGINT type is as a Java long.

• REAL:• The JDBC type REAL represents a "single precision" floating point number which supports

7 digits of mantissa.

• The corresponding SQL type REAL is defined in SQL-92 and is widely, though not universally, supported by the major databases.

• The recommended Java mapping for the REAL type is as a Java float.

Mapping SQL and Java Types (Contd.)

• DOUBLE:• The JDBC type DOUBLE represents a "double precision" floating point number which

supports 15 digits of mantissa.

• The corresponding SQL type is DOUBLE PRECISION, which is defined in SQL- 92 and is widely supported by the major databases.

• The recommended Java mapping for the DOUBLE type is as a Java double.

• FLOAT:• The JDBC type FLOAT is basically equivalent to the JDBC type DOUBLE. FLOAT represents

a "double precision" floating point number that supports 15 digits of mantissa.

• The corresponding SQL type FLOAT is defined in SQL-92. The SQL-92 standard leaves the precision of FLOAT up to the implementation, but in practice all the major databases supporting FLOAT support a mantissa precision of at least 15 digits.

• The recommended Java mapping for the FLOAT type is as a Java double.

Mapping SQL and Java Types (Contd.)

• DECIMAL and NUMERIC:• The JDBC types DECIMAL and NUMERIC are very similar. They both represent fixed-

precision decimal values.

• The corresponding SQL types DECIMAL and NUMERIC are defined in SQL-92 and are very widely implemented. These SQL types takes precision and scale parameters. The precision is the total number of decimal digits supported, and the scale is the number of decimal digits after the decimal point. The scale must always be less than or equal to the precision.

• The recommended Java mapping for the DECIMAL and NUMERIC types is java.math.BigDecimal, a Java type that also expresses fixed-point numbers with absolute precision. The java.math.BigDecimal type provides math operations to allow BigDecimal types to be added, subtracted, multiplied, and divided with other BigDecimal types, with integer types, and with floating point types.

Mapping SQL and Java Types (Contd.)

• DATE, TIME, and TIMESTAMP:• The JDBC DATE type represents a date consisting of day, month, and year. The

corresponding SQL DATE type is defined in SQL-92, but it is implemented by only a subset of the major databases. Some databases offer alternative SQL types that support similar semantics.

• The JDBC TIME type represents a time consisting of hours, minutes, and seconds. The corresponding SQL TIME type is defined in SQL-92, but it is implemented by only a subset of the major databases. As with DATE, some databases offer alternative SQL types that support similar semantics.

• The JDBC TIMESTAMP type represents DATE plus TIME plus a nanosecond field. The corresponding SQL TIMESTAMP type is defined in SQL-92, but it is implemented by only a very small number of databases.

Mapping SQL and Java Types (Contd.)

• Because the standard Java class java.util.Date does not match any of these three JDBC date-time types exactly, JDBC defines three subclasses of java.util.Date to correspond to the SQL types. They are:• java.sql.Date for SQL DATE information. The hour, minute, second, and millisecond

fields of the java.util.Date base class are set to zero.

• java.sql.Time for SQL TIME information. The year, month, and day fields of the java.util.Date base class are set to 1970, January, and 1. This is the "zero" date in the Java epoch.

• java.sql.Timestamp for SQL TIMESTAMP information. This class extends java.util.Date by adding a nanosecond field.

Mapping SQL and Java Types (Contd.)

• Exampleimport java.sql.*; //Import statement for JDBC

public class JDBCTest {

public static void main(String[] args)throws

SQLException, ClassNotFoundException {

String userName="root";

String password="MySql";

String URL = "jdbc:mysql://localhost/world";

String driverClass = "com.mysql.jdbc.Driver";

try{

Mapping SQL and Java Types (Contd.)

//Registering JDBC driver

Class.forName(driverClass);

//Creating connection to the database

Connection conn = DriverManager.getConnection(URL, userName, password);

//Starting database interaction

Statement stmt = conn.createStatement();

ResultSet results = stmt.executeQuery("select * from country");

ResultSetMetaData rsmd = results.getMetaData();

for (int i=1; i<=8; i++){

//Printing column names

System.out.print(rsmd.getColumnLabel(i)+"\t");

}

Mapping SQL and Java Types (Contd.)

while(results.next()){

String code = results.getString(1);

String name = results.getString(2);

String continent = results.getString(3);

String region = results.getString(4);

float sa = results.getFloat(5);

short iy=results.getShort(6);

int pop=results.getInt(7);

float le=results.getFloat(8);

System.out.println(code + "\t" + name + "\t" + continent+

"\t" +region+ "\t" + sa+"\t"+iy+"\t"+pop+"\t"+le);

}

Mapping SQL and Java Types (Contd.)

//Closing resultset, statement, and connection

results.close();

stmt.close();

conn.close();

}

catch(Exception e){

System.out.println(e);

}

}

}

Mapping SQL and Java Types (Contd.)

• Output:

Summary

• You have learnt that:• JDBC is an Application Programming Interface (API) that allows a Java

programmer to access any kind of tabular data, such as a database in a Java application.

• JDBC enables programmers to develop data-centric applications that can access and manipulate data from diverse range of databases.

• A JDBC driver is a collection of Java classes that enables a programmer to connect a Java application to a certain database.

• There are four types of JDBC drivers to connect with different types of databases.

• The core components of JDBC are provided under the java.sql package.