jdbc
jdbc
JDBC is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.
JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access
to an underlying database. Java can be used to write different types of executables, such as −
Java Applications
Java Applets
Java Servlets
Java Server Pages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take advantage of the
stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.
The first thing you need to do is check that you are set up properly. This involves the
following steps:
1. Install Java and JDBC on your machine.
To install both the Java tm platform and the JDBC API, simply follow the instructions for
downloading the latest release of the JDK tm (Java Development Kit tm ). When you download
the JDK, you will get JDBC as well.
Configuring Database:
Configuring a database is not at all difficult, but it requires special permissions and is normally
done by a database administrator.
First, open the control panel. You might find "Administrative tools" select it, again you may
find shortcut for "Data Sources (ODBC)". When you open the ―Data Source (ODBC)" 32bit
ODBC‖ icon, you‘ll see a "ODBC Data Source Administrator" dialog window with a number
of tabs, including ―User DSN,‖ ―System DSN,‖ ―File DSN,‖ etc., in which ―DSN‖ means ―Data
Source Name.‖ Select ―System DSN,‖. and add a new entry there, Select appropriate driver
for the data source or directory where database lives. You can name the entry anything you
want, assume here we are giving our data source name as"MySource".
JDBC was designed to keep simple things simple. This means that the JDBC API makes everyday
database tasks, like simple SELECT statements, very easy.
Import a package java.sql.* : This package provides you set of all classes that enables a
network interface between the front end and back end database.
• DriverManager will create a Connectionobject.
• java.sql.Connection interface represents a connection with a specific database. Methods of
connection is close(), creatStatement(), prepareStatement(), commit(), close() and
prepareCall()
• Statement interface used to interact with database via the execution of SQL statements.
Methods of this interface are executeQuery(), executeUpdate(), execute() andgetResultSet().
• A ResultSet is returned when you execute an SQL statement. It maintains a pointer to a row
within the tablur results. Mehods of this interface are next(), getBoolean(), getByte(),
getDouble(), getString() close() andgetInt().
Establishing a Connection
The first thing you need to do is establish a connection with the DBMS you want to use. This
involves two
steps: (1) loading the driver and (2) making the connection.
Loading Drivers: Loading the driver or drivers you want to use is very simple and involves
just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the
following code will load it
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use.Forinstance, if
the class name is jdbc.DriverXYZ , you would load the driver with the following line of
code:
Class.forName("jdbc.DriverXYZ");
Making the Connection: The second step in establishing a connection is to have the
appropriate driver connect to the DBMS. The following line of code illustrates the general idea:
Connection con = DriverManager.getConnection(url,"myLogin", "myPassword");
If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: .
The rest of the URL is generally your data source name or database system. So, if you are using
ODBC to access an ODBC data source called "MySource, " for example, your JDBC URL
could be jdbc:odbc:MySource . In place of " myLogin " you put the name you use to log in to
the DBMS; in place of " myPassword " you put your password for the DBMS. So if you log in
to your DBMS with a login name of " scott " and a password of "tiger" just these two lines of
code will establish aconnection:
String url = "jdbc:odbc:MySource";
Connection con = DriverManager.getConnection(url, "scott", "tiger");
The connection returned by the method DriverManager.getConnection is an open connection
you can use to create JDBC statements that pass your SQL statements to the DBMS. In the
previous example, con is an open connection, and we will use it in the dorth coming examples.
JDBC returns results in a ResultSet object, so we need to declare an instance of the class
ResultSet to hold our results. The following code demonstrates declaring the ResultSet object
rs and assigning the results of our earlier query toit:
ResultSet rs = stmt.executeQuery( "SELECT S_NAME, YEAR FROM STUDENT");
The following code accesses the values stored in the current row of rs. Each time the method
next is invoked, the next row becomes the current row, and the loop continues until there are
no more rows in rs .
String query = "SELECT COF_NAME, PRICE FROM STUDENT";
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
String s = rs.getString("S_NAME");
Integer i = rs.getInt("S_ID");
String c = rs.getString("COURSE");
String y = rs.getString(―YEAR‖);
System.out.println(i + " " + s + " " + c + " " + y);
}
Updating Tables
Suppose that after a period of time we want update the YEAR column in the table STUDENT.
The SQL statement to update one row might look likethis:
String updateString = "UPDATE STUDENT " +
"SET YEAR = IV WHERE S-NAME LIKE 'yStudent'";
Using the Statement object stmt , this JDBC code executes the SQL statement contained in
updateString :
stmt.executeUpdate(updateString);
Using try and catch Blocks:
Something else all the sample applications include is try and catch blocks. These are the Java
programming language's mechanism for handling exceptions. Java requires that when a method
throws an exception, there be some mechanism to handle it. Generally a catch block will catch
the exception and specify what happens (which you may choose to be nothing). In the sample
code, we use two try blocks and two catch blocks. The first try block contains the method
Class.forName, from the java.lang package. This method throws a ClassNotFoundException,
so the catch block immediately following it deals with that exception. The second try block
contains JDBC methods, which all throw SQLExceptions, so one catch block at the end of the
application can handle all of the rest of the exceptions that might be thrown because they
will all be SQLExceptionobjects.
Retrieving Exceptions
JDBC lets you see the warnings and exceptions generated by your DBMS and by the Java
compiler. To see exceptions, you can have a catch block print them out. For example, the
following two catch blocks from the sample code print out a message explaining the exception:
Try
{
// Code that could generate an exception goes here.
// If an exception is generated, the catch block below
// will print out information about it.
} catch(SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
}
Java Program to Join Contents of More than One Table & Display in JDBC:
Java supports many databases and for each database, we need to have their respective jar files to be placed in
the build path to proceed for JDBC connectivity. First, need to decide, which database we are using and
accordingly, we need to add the jars. For other databases like Progress, Cassandra, etc also we have jars and
need to include them in the build path. There are different kinds of joins available in MySQL and depends
upon the requirement, we can frame queries.
Join is a join that provides the facility to connect two tables are merged with each other according to a field
that is common and creates a new virtual table.
NATURAL JOIN: It is a type of join that retrieves data within specified tables to a specific field that is
matched.
NATURAL LEFT JOIN: In this operation, both tables are merged with each other according to common
fields but the priority is given to the first table in the database.
NATURAL RIGHT JOIN: It also the same as Natural left join but it retrieves the data from the second
table in the database.
Second table
CREATE TABLE `studentspersonaldetails` (
`id` int(6) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(30) NOT NULL,
`Address` varchar(30) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`reg_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;
In both tables, “Name” is the common column. 1st table specifies Gender, NeetMarks, Caste, etc whereas 2nd
table specifies the address, email, etc. Now only necessity is to create an SQL query to join the table which is
as follows:
SELECT * FROM " + "studentsdetails" + " NATURAL JOIN " + "studentspersonaldetails"
Now as this query is executed it retrieves data within specified tables to a specific field is matched, it will
match records in both tables depends upon “Name” column, implementing the Natural join concept in play.
Now the program depends upon the data present in both tables and for matching values of “Name” column in
both tables to get the desired output.
Implementation: Now executing the above query command with the help of the below program as per
Natural Join.
Java
// Display message
System.out.println(
"Joining 2 MySQL tables using Natural Join");
// Loading driver
// Jars(relevant) or mysql-connector-java-8.0.22
// in build path of project
Class.forName("com.mysql.cj.jdbc.Driver");
// Registering driver
// Beautification of output
System.out.format(
"%10s%10s%10s%10s%20s\n", name,
gender, caste, neetMarks, email);
}
Output :
Transaction Processing by JDBC:
Transactions enable you to control if, and when, changes are applied to the database. It treats a single SQL
statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction
fails.
To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default,
use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you
turn off auto-commit. You can pass a boolean true to turn it back on again.
For example, if you have a Connection object named conn, code the following to turn off auto-commit −
conn.setAutoCommit(false);
Commit & Rollback
Once you are done with your changes and you want to commit the changes then call commit() method on
connection object as follows −
conn.commit( );
Otherwise, to roll back updates to the database made using the Connection named conn, use the following code
−
conn.rollback( );
The following example illustrates the use of a commit and rollback object −
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback();
}
In this case, none of the above INSERT statement would success and everything would be rolled back.
Using Savepoints
The new JDBC 3.0 Savepoint interface gives you the additional transactional control. Most modern
DBMS, support savepoints within their environments such as Oracle's PL/SQL.
When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a
savepoint, you can use the rollback method to undo either all the changes or only the changes made after the
savepoint.
The Connection object has two new methods that help you manage savepoints −
setSavepoint(String savepointName) − Defines a new savepoint. It also returns a Savepoint object.
releaseSavepoint(Savepoint savepointName) − Deletes a savepoint. Notice that it requires a Savepoint
object as a parameter. This object is usually a savepoint generated by the setSavepoint() method.
There is one rollback (String savepointName) method, which rolls back work to the specified savepoint.
The following example illustrates the use of a Savepoint object –
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
//set a Savepoint
Savepoint savepoint1 = conn.setSavepoint("Savepoint1");
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Tez')";
stmt.executeUpdate(SQL);
// If there is no error, commit the changes.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback(savepoint1);
}
In this case, none of the above INSERT statement would success and everything would be rolled back.
Stored Procedures in Java DB:
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task, and
they are used to encapsulate a set of operations or queries to execute on a database server. For example,
operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures
executed by application code. Stored procedures can be compiled and executed with different parameters and
results, and they can have any combination of input, output, and input/output parameters.
Note that stored procedures are supported by most DBMSs, but there is a fair amount of variation in their
syntax and capabilities. Consequently, the tutorial contains two
samples, StoredProcedureJavaDBSample.java and StoredProcedureMySQLSample.java, that demonstrate how
to create stored procedures in Java DB and MySQL, respectively.
Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the
CallableStatement object, which would be used to execute a call to a database stored procedure.
Creating CallableStatement Object
Let us write stored procedure for MySQL as follows to create it in EMP database.
DELIMITER $$
DELIMITER ;
Three types of parameters exist − IN, OUT, and INOUT. The PreparedStatement object only uses the IN
parameter. The CallableStatement object can use all the three.
Here are the definitions of each −
Parameter Description
IN A parameter whose value is unknown when the SQL statement is created. You
bind values to IN parameters with the setXXX() methods.
OUT A parameter whose value is supplied by the SQL statement it returns. You
retrieve values from the OUT parameters with the getXXX() methods.
INOUT A parameter that provides both input and output values. You bind variables with
the setXXX() methods and retrieve values with the getXXX() methods.
The following code snippet shows how to employ the Connection.prepareCall() method to instantiate
a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
...
}
The String variable SQL represents the stored procedure, with parameter placeholders.
Using CallableStatement objects is much like using PreparedStatement objects. You must bind values to all the
parameters before executing the statement, or you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement object;
use the setXXX() method that corresponds to the Java data type you are binding.
When you use OUT and INOUT parameters, you must employ an additional CallableStatement method,
registerOutParameter(). The registerOutParameter() method binds the JDBC data type to the data type the
stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate
getXXX() method. This method casts the retrieved value of SQL type to a Java data type.
Closing CallableStatement Object
Just as you close other Statement object, for the same reason you should also close the CallableStatement
object.
A simple call to the close() method will do the job. If you close the Connection object first, it will close the
CallableStatement object as well. However, you should always explicitly close the CallableStatement object to
ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e) {
...
}
finally {
cstmt.close();
}
JDBC SQL Escape Syntax
The escape syntax gives you the flexibility to use database specific features unavailable to you by using
standard JDBC methods and properties.
The general SQL escape syntax format is as follows −
{keyword 'parameters'}
Here are the following escape sequences, which you would find very useful while performing the JDBC
programming −
d, t, ts Keywords
They help identify date, time, and timestamp literals. As you know, no two DBMSs represent time and date the
same way. This escape syntax tells the driver to render the date or time in the target database's format. For
Example −
{d 'yyyy-mm-dd'}
Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-09-03'} is March 9, 2009.
Here is a simple example showing how to INSERT date in a table −
//Create a Statement object
stmt = conn.createStatement();
//Insert data ==> ID, First Name, Last Name, DOB
String sql="INSERT INTO STUDENTS VALUES" +
"(100,'Zara','Ali', {d '2001-12-16'})";
stmt.executeUpdate(sql);
Similarly, you can use one of the following two syntaxes, either t or ts −
{t 'hh:mm:ss'}
Where hh = hour; mm = minute; ss = second. Using this syntax {t '13:30:29'} is 1:30:29 PM.
{ts 'yyyy-mm-dd hh:mm:ss'}
This is combined syntax of the above two syntax for 'd' and 't' to represent timestamp.
escape Keyword
This keyword identifies the escape character used in LIKE clauses. Useful when using the SQL wildcard %,
which matches zero or more characters. For example −
String sql = "SELECT symbol FROM MathSymbols
WHERE symbol LIKE '\%' {escape '\'}";
stmt.execute(sql);
If you use the backslash character (\) as the escape character, you also have to use two backslash characters in
your Java String literal, because the backslash is also a Java escape character.
fn Keyword
This keyword represents scalar functions used in a DBMS. For example, you can use SQL function length to
get the length of a string −
{fn length('Hello World')}
This returns 11, the length of the character string 'Hello World'.
call Keyword
This keyword is used to call the stored procedures. For example, for a stored procedure requiring an IN
parameter, use the following syntax −
{call my_procedure(?)};
For a stored procedure requiring an IN parameter and returning an OUT parameter, use the following syntax −
{? = call my_procedure(?)};
oj Keyword
This keyword is used to signify outer joins. The syntax is as follows −
{oj outer-join}
Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-join} on search-condition. For
example −
String sql = "SELECT Employees
FROM {oj ThisTable RIGHT
OUTER JOIN ThatTable on id = '100'}";
stmt.execute(sql);