JDBC Notes 1
JDBC Notes 1
www.peoplestrategists.com
Java Database Connectivity
(JDBC)
}
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 Statement
interface.
• 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 Connection
interface, 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 Connection
interface 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 Connection
interface.
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,ename
varchar(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.)
• 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";
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.