JDBC Lecture
JDBC Lecture
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
● Making a connection to a database.
● Creating SQL or MySQL statements.
● Executing SQL or MySQL queries in the database.
● Viewing & Modifying the resulting records.
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 ServerPages (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.
Create Database
The CREATE DATABASE statement is used for creating a new database. The syntax is
−
SQL> CREATE DATABASE DATABASE_NAME;
Example
The following SQL statement creates a Database named EMP −
SQL> CREATE DATABASE EMP;
Drop Database
The DROP DATABASE statement is used for deleting an existing database. The syntax
is −
SQL> DROP DATABASE DATABASE_NAME;
Note: To create or drop a database you should have administrator privilege on your
database server. Be careful, deleting a database would loss all the data stored in the
database.
Create Table
The CREATE TABLE statement is used for creating a new table. The syntax is −
SQL> CREATE TABLE table_name
(
column_name column_data_type,
column_name column_data_type,
column_name column_data_type
...
);
Example
The following SQL statement creates a table named Employees with four columns −
SQL> CREATE TABLE Employees
(
id INT NOT NULL,
age INT NOT NULL,
first VARCHAR(255),
last VARCHAR(255),
PRIMARY KEY ( id )
);
Drop Table
The DROP TABLE statement is used for deleting an existing table. The syntax is −
SQL> DROP TABLE table_name;
Example
The following SQL statement deletes a table named Employees −
SQL> DROP TABLE Employees;
INSERT Data
The syntax for INSERT, looks similar to the following, where column1, column2, and so
on represents the new data to appear in the respective columns −
SQL> INSERT INTO table_name VALUES (column1, column2, ...);
Example
The following SQL INSERT statement inserts a new row in the Employees database
created earlier −
SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
SELECT Data
The SELECT statement is used to retrieve data from a database. The syntax for
SELECT is −
SQL> SELECT column_name, column_name, ...
FROM table_name
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=,
as well as the BETWEEN and LIKE operators.
Example
The following SQL statement selects the age, first and last columns from the
Employees table, where id column is 100 −
SQL> SELECT first, last, age
FROM Employees
WHERE id = 100;
The following SQL statement selects the age, first and last columns from the
Employees table where first column contains Z
ara −
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE '%Zara%';
UPDATE Data
The UPDATE statement is used to update data. The syntax for UPDATE is −
SQL> UPDATE table_name
SET column_name = value, column_name = value, ...
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=,
as well as the BETWEEN and LIKE operators.
Example
The following SQL UPDATE statement changes the age column of the employee
whose id is 100 −
SQL> UPDATE Employees SET age=20 WHERE id=100;
DELETE Data
The DELETE statement is used to delete data from tables. The syntax for DELETE is −
SQL> DELETE FROM table_name WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=,
as well as the BETWEEN and LIKE operators.
Example
The following SQL DELETE statement deletes the record of the employee whose id is
100 −
SQL> DELETE FROM Employees WHERE id=100;
To start developing with JDBC, you should setup your JDBC environment by following
the steps shown below. We assume that you are working on a Windows platform.
Install Java
Install J2SE Development Kit 5.0 (JDK 5.0) from Java Official Site.
Make sure following environment variables are set as described below −
● JAVA_HOME: This environment variable should point to the directory where you
installed the JDK, e.g. C:\Program Files\Java\jdk1.5.0.
● CLASSPATH: This environment variable should have appropriate paths set, e.g.
C:\Program Files\Java\jdk1.5.0_20\jre\lib.
● PATH: This environment variable should point to appropriate JRE bin, e.g.
C:\Program Files\Java\jre1.5.0_20\bin.
It is possible you have these variable set already, but just to make sure here's how to
check.
● Go to the control panel and double-click on System. If you are a Windows XP
user, it is possible you have to open Performance and Maintenance before you
will see the System icon.
● Go to the Advanced tab and click on the Environment Variables.
● Now check if all the above mentioned variables are set properly.
You automatically get both JDBC packages java.sql and javax.sql, when you install
J2SE Development Kit 5.0 (JDK 5.0).
Install Database
The most important thing you will need, of course is an actual running database with a
table that you can query and modify.
Install a database that is most suitable for you. You can have plenty of choices and
most common are −
● MySQL DB: MySQL is an open source database. You can download it from
MySQL Official Site. We recommend downloading the full Windows installation.
In addition, download and install MySQL Administrator as well as MySQL Query
Browser. These are GUI based tools that will make your development much
easier.
Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a
convenient directory. For the purpose of this tutorial we will assume that you
have installed the driver at C:\Program Files\MySQL\mysql-connector-java-5.1.8.
Accordingly, set CLASSPATH variable to C:\Program
Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar.
Your driver version may vary based on your installation.
● PostgreSQL DB: PostgreSQL is an open source database. You can download it
from PostgreSQL Official Site.
The Postgres installation contains a GUI based administrative tool called
pgAdmin III. JDBC drivers are also included as part of the installation.
● Oracle DB: Oracle DB is a commercial database sold by Oracle . We assume
that you have the necessary distribution media to install it.
Oracle installation includes a GUI based administrative tool called Enterprise
Manager. JDBC drivers are also included as a part of the installation.
Step 1
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Note: The path to mysqld.exe may vary depending on the install location of MySQL
on your system. You can also check documentation on how to start and stop your
database server.
Step 2
Start the database server by executing the following command, if it is already not
running.
C:\Program Files\MySQL\bin>mysqld
C:\Program Files\MySQL\bin>
Step 3
Create the EMP database by executing the following command −
C:\Program Files\MySQL\bin> mysqladmin create EMP -u root -p
Enter password: ********
C:\Program Files\MySQL\bin>
Create Table
To create the Employees table in EMP database, use the following steps −
Step 1
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>
Step 3
Create the table Employee as follows −
mysql> use EMP;
mysql> create table Employees
-> (
-> id int not null,
-> age int not null,
-> first varchar (255),
-> last varchar (255)
-> );
Query OK, 0 rows affected (0.08 sec)
mysql>
Sample Code
This sample example can serve as a template when you need to create your own
JDBC application in the future.
This sample code has been written based on the environment and database setup
done in the previous chapter.
Copy and paste the following example in FirstExample.java, compile and run as
follows −
//STEP 1. Import required packages
import java.sql.*;
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("
last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Now let us compile the above example as follows −
C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces the following result −
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of
driver.
Type 2: JDBC-Native API
In a 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.
If we change the Database, we have to change the native API, as it is specific to a
database and they are mostly obsolete now, but you may realize some speed increase
with a Type 2 driver, because it eliminates ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Approach I - Class.forName()
The most common approach to register a driver is to use Java's Class.forName()
method, to dynamically load the driver's class file into memory, which automatically
registers it. This method is preferable because it allows you to make the driver
registration configurable and portable.
The following example uses Class.forName( ) to register the Oracle driver −
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
You can use getInstance() method to work around noncompliant JVMs, but then you'll
have to code for two extra Exceptions as follows −
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}
Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method.
You should use the registerDriver() method if you are using a non-JDK compliant JVM,
such as the one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver −
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
All the highlighted part in URL format is static and you need to change only the
remaining part as per your database setup.
CallableStatement Use this when you want to access the database stored
procedures. The CallableStatement interface can also
accept runtime input parameters.
Parameter Description
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 (S
QL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
The String variable SQL, represents the stored procedure, with parameter
placeholders.
Using the CallableStatement objects is much like using the 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 that 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.
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you
will automatically get one that is TYPE_FORWARD_ONLY.
Type Description
Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency
type, you will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
All our examples written so far can be written as follows, which initializes a Statement
object to create a forward-only, read only ResultSet object −
try {
Statement stmt = conn.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) {
....
}
finally {
....
}
Moves the cursor to the previous row. This method returns false if the
previous row is off the result set.
Moves the cursor to the next row. This method returns false if there are no
more rows in the result set.
Returns the int in the current row in the column named columnName.
Returns the int in the current row in the specified column index. The column
index starts at 1, meaning the first column of a row is 1, the second column of
a row is 2, and so on.
Similarly, there are get methods in the ResultSet interface for each of the eight Java
primitive types, as well as common types such as java.lang.String, java.lang.Object,
and java.net.URL.
There are also methods for getting SQL data types java.sql.Date, java.sql.Time,
java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. Check the documentation for
more information about using these SQL data types.
For a better understanding, let us study Viewing - Example Code.
Updating a Result Set
The ResultSet interface contains a collection of update methods for updating the data
of a result set.
As with the get methods, there are two update methods for each data type −
● One that takes in a column name.
● One that takes in a column index.
For example, to update a String column of the current row of a result set, you would
use one of the following updateString() methods −
Similar to the previous method, except that the column is specified by its
name instead of its index.
Updates the current row by updating the corresponding row in the database.
Refreshes the data in the result set to reflect any recent changes in the
database.
Inserts a row into the database. This method can only be invoked when the
cursor is pointing to the insert row.
The JDBC driver converts the Java data type to the appropriate JDBC type, before
sending it to the database. It uses a default mapping for most data types. For
example, a Java int is converted to an SQL INTEGER. Default mappings were created
to provide consistency between drivers.
The following table summarizes the default JDBC data type that the Java data type is
converted to, when you call the setXXX() method of the PreparedStatement or
CallableStatement object or the ResultSet.updateXXX() method.
SQL JDBC/Java setXXX updateXXX
JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The
ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and
updateRef() methods that enable you to directly manipulate the respective data on the
server.
The setXXX() and updateXXX() methods enable you to convert specific Java types to
specific JDBC data types. The methods, setObject() and updateObject(), enable you
to map almost any Java type to a JDBC data type.
ResultSet object provides corresponding getXXX() method for each data type to
retrieve column value. Each method can be used with column name or by its ordinal
position.
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(f alse);
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.
Exception handling allows you to handle exceptional conditions such as
program-defined errors in a controlled fashion.
When an exception condition occurs, an exception is thrown. The term thrown means
that current program execution stops, and the control is redirected to the nearest
applicable catch clause. If no applicable catch clause exists, then the program's
execution ends.
JDBC Exception handling is very similar to the Java Exception handling but for JDBC,
the most common exception you'll deal with is java.sql.SQLException.
SQLException Methods
An SQLException can occur both in the driver and the database. When such an
exception occurs, an object of type SQLException will be passed to the catch clause.
The passed SQLException object has the following methods available for retrieving
additional information about the exception −
Method Description
By utilizing the information available from the Exception object, you can catch an
exception and continue your program appropriately. Here is the general form of a try
block −
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
Example
Study the following example code to understand the usage of try....catch...finally
blocks.
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("
last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
Now, let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result if there is no problem,
otherwise the corresponding error would be caught and error message would be
displayed −
C:\>java JDBCExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
Try the above example by passing wrong database name or wrong username or
password and check the result.
Batch Processing allows you to group related SQL statements into a batch and submit
them with one call to the database.
When you send several SQL statements to the database at once, you reduce the
amount of communication overhead, thereby improving performance.
● JDBC drivers are not required to support this feature. You should use the
DatabaseMetaData.supportsBatchUpdates() method to determine if the target
database supports batch update processing. The method returns true if your
JDBC driver supports this feature.
● The addBatch() method of Statement, PreparedStatement, and
CallableStatement is used to add individual statements to the batch. The
executeBatch() is used to start the execution of all the statements grouped
together.
● The executeBatch() returns an array of integers, and each element of the array
represents the update count for the respective update statement.
● Just as you can add statements to a batch for processing, you can remove them
with the clearBatch() method. This method removes all the statements you
added with the addBatch() method. However, you cannot selectively choose
which statement to remove.
Example
The following code snippet provides an example of a batch update using Statement
object −
// Create statement object
Statement stmt = conn.createStatement();
// Set auto-commit to false
conn.setAutoCommit(false);
// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(200,'Zia', 'Ali', 30)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create one more SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(201,'Raj', 'Kumar', 35)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create one more SQL statement
String SQL = "UPDATE Employees SET age = 35 " +
"WHERE id = 100";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);
// Create an int[] to hold returned values
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();
For a better understanding, let us study the Batching - Example Code.
Parameter Description
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 (S
QL);
. . .
}
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.
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 l ength 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);
A PreparedStatement object has the ability to use input and output streams to supply
parameter data. This enables you to place entire files into database columns that can
hold large values, such as CLOB and BLOB data types.
There are following methods, which can be used to stream data −
● setAsciiStream(): This method is used to supply large ASCII values.
● setCharacterStream(): This method is used to supply large UNICODE values.
● setBinaryStream(): This method is used to supply large binary values.
The setXXXStream() method requires an extra parameter, the file size, besides the
parameter placeholder. This parameter informs the driver how much data should be
sent to the database using the stream.
Example
Consider we want to upload an XML file XML_Data.xml into a database table. Here is
the content of this XML file −
<?xml version="1.0"?>
<Employee>
<id>100</id>
<first>Zara</first>
<last>Ali</last>
<Salary>10000</Salary>
<Dob>18-08-1978</Dob>
<Employee>
Keep this XML file in the same directory where you are going to run this example.
This example would create a database table XML_Data and then file XML_Data.xml
would be uploaded into this table.
Copy and past the following example in JDBCExample.java, compile and run as
follows −
// Import required packages
import java.sql.*;
import java.io.*;
import java.util.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
Statement stmt = null;
ResultSet rs = null;
try{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//Create a Statement object and build table
stmt = conn.createStatement();
createXMLTable(stmt);
//Open a FileInputStream
File f = new File("XML_Data.xml");
long fileLength = f.length();
FileInputStream fis = new FileInputStream(f);
//Create PreparedStatement and stream data
String SQL = "INSERT INTO XML_Data VALUES (?,?)";
pstmt = conn.prepareStatement(SQL);
pstmt.setInt(1,100);
pstmt.setAsciiStream(2,fis,(int)fileLength);
pstmt.execute();
//Close input stream
fis.close();
/ / Do a query to get the row
SQL = "SELECT Data FROM XML_Data WHERE id=100";
rs = stmt.executeQuery (SQL);
// Get the first row
if (rs.next ()){
//Retrieve data from input stream
InputStream xmlInputStream = rs.getAsciiStream (1);
int c;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while (( c = xmlInputStream.read ()) != -1)
bos.write(c);
//Print results
System.out.println(bos.toString());
}
// Clean-up environment
rs.close();
stmt.close();
pstmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(pstmt!=null)
pstmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
public static void createXMLTable(S tatement stmt)
throws SQLException{
System.out.println("Creating XML_Data table..." );
//Create SQL Statement
String streamingDataSql = "CREATE TABLE XML_Data " +
"(id INTEGER, Data LONG)";
//Drop table first if it exists.
try{
stmt.executeUpdate("DROP TABLE XML_Data");
}catch(SQLException se){
}// do nothing
//Build table.
stmt.executeUpdate(streamingDataSql);
}//end createXMLTable
}//end JDBCExample
Now let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Connecting to database...
Creating XML_Data table...
<?xml version="1.0"?>
<Employee>
<id>100</id>
<first>Zara</first>
<last>Ali</last>
<Salary>10000</Salary>
<Dob>18-08-1978</Dob>
<Employee>
Goodbye!
C:\>