JDBC Tutorial http://www.jdbctutorial.net JDBC Tutorial, Spring JDBC, Hibernate Tutorial, JPA, EJB .30 Tutorial Wed, 08 Feb 2012 13:30:14 +0000 en hourly 1 http://wordpress.org/?v=3.3.1 Amazon Launches DynamoDB http://www.jdbctutorial.net/2012/02/amazon-launches-dynamodb/ http://www.jdbctutorial.net/2012/02/amazon-launches-dynamodb/#comments Thu, 02 Feb 2012 11:13:58 +0000 Tousif Khan http://www.jdbctutorial.net/?p=219 Amazon-DynamoDB

Amazon Web Services launched DynamoDB, as an NoSQL database designed for Internet scale web applications. The announcement is interesting for a couple of reasons. First, AWS’s database services provide reasonably priced, highly-available database services delivered on fast storage architecture based on Solid State Drives (SSD).

At $1 per month for a gigabyte of SSD managed, durable and highly-available storage, AWS is clearly going for the jugular early on other managed NoSQL solutions. Moreover, AWS has the added advantage of offering multiple other services in tandem with DynamoDB that are attractive when compared to using multiple hosted services.

However, the bigger question is what is the business potential for this service? A simple Google search on “Managed NoSQL Databases” results in numerous hits about DynamoDB, but forces one to dig to find the competitors in this space.

]]>
http://www.jdbctutorial.net/2012/02/amazon-launches-dynamodb/feed/ 0
Using RowCallbackHandler in Spring JdbcTemplate http://www.jdbctutorial.net/2011/10/using-rowcallbackhandler-in-spring-jdbctemplate/ http://www.jdbctutorial.net/2011/10/using-rowcallbackhandler-in-spring-jdbctemplate/#comments Thu, 27 Oct 2011 08:47:50 +0000 Tousif Khan http://www.jdbctutorial.net/?p=214 CallbackHandler is a interface used by JdbcTemplate’s query methods. This interface cantains only one method with the signature in the following code snippet.

The implementation class of this interface needs to implements the processRow() method, which take responsibility to process each row of data in the ResultSet. The processRow() method should not call next() on the ResultSet. It requiredd to extract values of the current row and process the data on per-row basis.

Usually the processRow() method does not need to worry about handling the SQLException, the SQLException will be caught and handle by JdbcTemplate class calling this implementation.

Following code shows ProductResult class implementing RowCallbackHandler interface..

]]>
http://www.jdbctutorial.net/2011/10/using-rowcallbackhandler-in-spring-jdbctemplate/feed/ 0
Using ResultSetExcractor in Spring JdbcTemplate http://www.jdbctutorial.net/2011/10/using-resultsetexcractor-in-spring-jdbctemplate/ http://www.jdbctutorial.net/2011/10/using-resultsetexcractor-in-spring-jdbctemplate/#comments Thu, 27 Oct 2011 08:41:41 +0000 Tousif Khan http://www.jdbctutorial.net/?p=212 JdbcTemplate class includes query methods to prepare and execute the SQL queries. The Spring JDBC abstraction framewor provides three different types of callbacks to read the results after executing the SQL query using query() methods.

  • ResultSetExtractor
  • RowCallbackHandler
  • RowMapper

Let’s start our discussion with ResultSetExtractor.
ResultSetExtractor contains only one method with the regnature shown in the following code snippet.

The implementation class of this interface need to implements the extractData() metod, which takes the responsibility of extracting results from a ResultSet, but it does not need to worry about handling SQLException raised while extracting the results.

The SQLException will be caught and handle by JdbcTemplate class calling this implementation.

]]>
http://www.jdbctutorial.net/2011/10/using-resultsetexcractor-in-spring-jdbctemplate/feed/ 0
JdbcTemplate to execute SQL DML Statements http://www.jdbctutorial.net/2011/10/jdbctemplate-to-execute-sql-dml-statements/ http://www.jdbctutorial.net/2011/10/jdbctemplate-to-execute-sql-dml-statements/#comments Thu, 27 Oct 2011 08:35:50 +0000 Tousif Khan http://www.jdbctutorial.net/?p=209 JdbcTemplate proveides update() methods for executing single SQL DML statement. It support JDBC statement and PreparedStatement style of eecuting the SQL statements.

Following example demonstrates all the update methods of JdbcTemplate. To make this example simple, we are using ‘Product’ table. Following SQL Script show the table description.

Following Dao Interface shows the minimum methods representing the Product table. This Dao containing only the methods to creating , updating and deleting the Product table Records.

You Product bean look likes….

Now write the ProductDaoImpl…

Following code shows the PreparedStatementCreator implementation MyPreparedStatementCreator, which is designed to insert a new Product Records.

Following code is a PreparedStatementSetter implemetation MyPreparedStatementSetter, which is designed to set the Product details for updating the Product.

After writing all the java code, new its time to configure the JdbcTemplate class in Spring XML file.

Now write a client to test that code….

]]>
http://www.jdbctutorial.net/2011/10/jdbctemplate-to-execute-sql-dml-statements/feed/ 0
JDBC ResultSet Metadata using Oracle http://www.jdbctutorial.net/2011/10/jdbc-resultset-metadata-using-oracle/ http://www.jdbctutorial.net/2011/10/jdbc-resultset-metadata-using-oracle/#comments Thu, 20 Oct 2011 03:46:15 +0000 Tousif Khan http://www.jdbctutorial.net/?p=207 In the simplest meaning, metadata is data about data.When you apply this to database, metadata is information about database data, or about table data. Examples of metadata are descriptions of the tables and column attributes, column type etc

The JDBC API enables you to uncover metadata about a database and a query’s result set using the DatabaseMetaData and ResultSetMetaData interfaces, respectively. The first interface enables you to obtain information about your database’s attributes and make runtime decisions based around that information. The second interface enables you to determine the attributes — such as number of columns, names, and data types — for a result set.

The ResultSetMetaData Interface: The ResultSetMetaData interface provides descriptive information about the columns in a result set such as the number of columns it contains or each column’s data type. The interface does not provide information regarding the database or the number of rows in the result set.

Creating ResultSetMetaData Object: The ResultSetMetaData object is instantiated from a valid ResultSet object. The following code snippet creates a ResultSetMetaData object, rsmd, that contains the column metadata for the entire Employees table:

Connection con = DriverManager.getConnection(url,userName,password);
Statement stmt = conn.createStatement();
//Create a result set
ResultSet rs = stmt.executeQuery("SELECT * FROM Employees");
//Obtain the result set metadata
ResultSetMetaData rsmd = rs.getMetaData();

Using ResultSetMetaData Interface: The ResultSetMetaData interface provides you with numerous methods for retrieving information about the result set. You call the various setter and getter methods to retrieve data from the ResultSetMetaData object. Following is the example given to know more about ResultSetMetaData.

import java.sql.*;
import java.util.*;
 
public class ResultSetMDDemo {
 
	public static void main(String s[]) throws Exception {
	Driver d =(Driver)Class.forName("oracle.jdbc.driver.OracleDriver")
			.newInstance();
 
	Properties p = new Properties();
	p.put("user", "scott");
	p.put("password", "tiger");
 
	Connection con = d.connect("jdbc:oracle:thin:@mysys:1521:khan",p);
	Statement st = con.createStatement();
	ResultSet rs = st.executeQuery("select * from "+s[0]);
 
	//Table name is taken as an command line arg
	ResultSetMetaData rsmd = rs.getMetaData();
	System.out.println("Table Name : "+s[0]);
	int colcount = rsmd.getColumnCount();
 
	for (int i=1;i<=colcount;i++) {
		System.out.print(rsmd.getColumnName(i)+"\t");
		System.out.println(rsmd.getColumnTypeName(i));
	}//for
 
	con.close();
	}//main
 
}//class
]]>
http://www.jdbctutorial.net/2011/10/jdbc-resultset-metadata-using-oracle/feed/ 0
Using JDBC Database Metadata http://www.jdbctutorial.net/2011/10/using-jdbc-database-metadata/ http://www.jdbctutorial.net/2011/10/using-jdbc-database-metadata/#comments Thu, 20 Oct 2011 03:40:17 +0000 Tousif Khan http://www.jdbctutorial.net/?p=205 The java.sql.DatabaseMetaData is an interface implemented by the JDBC driver provired. The DatabaseMetaData interface encapsulate all the information related to the database and driver. Using this interface, you can get more detail information about database, all the table in the database, catalog name, table type (view, table, system table, synonym ) etc.

Creating DatabaseMetaData Object: A Connection object represents a database connection and also instantiates a DatabaseMetaData object with the getMetaData() method. The DatabaseMetaData object holds information for the database to which the
Connection object is connected. The following code snippet illustrates how to create a DatabaseMetaData object:

Connection con = DriverManager.getConnection(url,userName,password);
DatabaseMetaData dmd = conn.getMetaData();

Using DatabaseMetaData Interface: The DatabaseMetaData object has many methods and properties that provide a lot of information about a database. In fact, when getting started with the DatabaseMetaData interface you may find the number of methods overwhelming.

Following is the code to get all the table from given SCHEMA. It uses Data Source Name to established Connection.


import java.sql.*;
public class  DatabaseMetaDataDemo{

public static void main(String[] args)
	throws Exception
{
	Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	Connection con =
	DriverManager.getConnection("jdbc:odbc:khanDSN",
				"scott","tiger");

	DatabaseMetaData db=con.getMetaData();
	String[] types={"TABLE"};
	ResultSet rs=db.getTables(null,"scott",args[0],types);
	System.out.print("Catalog\t");
	System.out.print("Table_Schema\t");
	System.out.print("Table_Name\t");
	System.out.print("Remarks\t\t");
	System.out.println("Types_Catalog");

	System.out.println("-----------------------------------");
	while(rs.next())
	{
		System.out.print(rs.getString(1)+"\t");
		System.out.print(rs.getString(2)+"\t\t");
		System.out.print(rs.getString(3)+"\t\t");
		System.out.print(rs.getString(4)+"\t\t");
		System.out.println(rs.getString(5));
	}//while
	rs.close();
	con.close();
	}//main

}//class
]]>
http://www.jdbctutorial.net/2011/10/using-jdbc-database-metadata/feed/ 0
Oracle WebRowSet Tutorial using JDBC http://www.jdbctutorial.net/2011/10/oracle-webrowset-tutorial-using-jdbc/ http://www.jdbctutorial.net/2011/10/oracle-webrowset-tutorial-using-jdbc/#comments Thu, 20 Oct 2011 03:06:17 +0000 Tousif Khan http://www.jdbctutorial.net/?p=200 The WebRowSet class extends the CachedRowSet class, which lets you use the same properties and methods as well as operate in disconnected mode. However, the WebRowSet object can generate XML documents representing itself. You can use these documents to create copies of the WebRowSet object, which makes it easy for you to distribute the information across the Web and through firewalls using HTTP. It will likely play a major role as the Web-services architecture continues to develop.

WebRowSet to generate and use XML
The WebRowSet class has the extra benefit of being able to represent itself as an XML
document. You can use the XML file just as you would a serialized CachedRowSet or WebRowSet object. For example, you can send it to a network client or store it for archival purposes.

In addition to generating an XML file, the WebRowSet object can also use an XML file to populate itself. The client can use the XML file you sent to build a duplicate WebRowSet object. The client can then update the data, generate a new XML file containing the
changes, and send it to a JSP page or servlet, which in turn could update the data source.

Following is a code of WebRowSet implemented by Oracle Driver.

import java.io.*;
import java.sql.SQLException;
import oracle.jdbc.rowset.OracleWebRowSet;

public class WebRowSetDemo {

//Constant representing the XML file
private static String WRS_FILE_LOC ="wrs.xml";

public final static void main(String[] args) throws Exception {

try {
	//Instantiate a WebRowSet object
	OracleWebRowSet wrs = new OracleWebRowSet();

	//Load driver and set connection parameters
	Class.forName("oracle.jdbc.driver.OracleDriver");
	wrs.setUrl("jdbc:oracle:thin:@localhost:1521:khan_db");
	wrs.setUsername("scott");
	wrs.setPassword("tiger");

	//Configure command and execute
	System.out.println("Connecting to data source and " +
	"generating XML document.");
	String sql = "SELECT ssn, name FROM Employees";
	wrs.setCommand(sql);
	wrs.execute();

	//Write XML out to file
	System.out.println("Writing XML to file: " + WRS_FILE_LOC);
	FileWriter fw = new FileWriter(WRS_FILE_LOC);
	wrs.writeXml(fw);

	fw.close();
	wrs.close();

	System.out.println("Finished writing XML file.");
	}catch (SQLException se){
		se.printStackTrace();
	}catch (Exception ex) {
		ex.printStackTrace();
	}
	System.out.println("Goodbye!");
}//end main()
}//end WebRS class
]]>
http://www.jdbctutorial.net/2011/10/oracle-webrowset-tutorial-using-jdbc/feed/ 1
Oracle CachedRowSet Tutorial with JDBC http://www.jdbctutorial.net/2011/10/oracle-cachedrowset-tutorial-with-jdbc/ http://www.jdbctutorial.net/2011/10/oracle-cachedrowset-tutorial-with-jdbc/#comments Thu, 20 Oct 2011 02:55:54 +0000 Tousif Khan http://www.jdbctutorial.net/?p=197 The CachedRowSet class provides the same functionality as the JdbcRowSet class, with one important difference: a CachedRowSet object can operate in a disconnected environment. As a result, it can function without a JDBC driver present. Once you populate a CachedRowSet object with data you may send it over the network to thin clients (PDA’s etc.), provide it to sales professionals on their laptops, or serialize it for data archiving. The advantage of the CachedRowSet object is that the client to whom you send the object does not need the JDBC driver.

JdbcRowSet Vs. CachedRowSet
The JdbcRowSet is a connected rowset that requires a continuous connection with the data source and you cannot serialize a JdbcRowSet object, which limits your ability to distribute or save the object.The CachedRowSet class overcomes those limitations. It provides a disconnected and serializable implementation of the RowSet interface.

To operate in a disconnected state a CachedRowSet object creates a virtual database by caching the tabular information it receives from the data source. Storing the data internally
makes the object self-contained and thereby allows it to operate while disconnected.
Following is the tutorial of CachedRowSet which is using serialization to read and write the Object.

import java.io.*;
import java.sql.SQLException;
import oracle.jdbc.rowset.OracleCachedRowSet;
 
public class CachedRowSetDemo {
 
//Constant to hold file name used to store the CachedRowSet
private final static String CRS_FILE_LOC ="cachedrs.crs";
 
public static void main(String[] args) throws Exception {
 
try {
	//Create serialized CachedRowSet
	writeCachedRowSet();
	//Create CachedRowSet from serialized object
	OracleCachedRowSet crs = readCachedRowSet();
	//Display values
	while(crs.next()){
		System.out.print("SSN: " + crs.getInt("ssn"));
		System.out.print(", Name: " + crs.getString("name"));
		System.out.print(", Salary: $" + crs.getDouble("salary"));
		System.out.print(", HireDate: " + crs.getDate("hiredate"));
		System.out.println();
	}
	//Close resource
	crs.close();
	}catch (SQLException se){
	se.printStackTrace();
	}catch (Exception ex) {
	ex.printStackTrace();
}
}//end main
 
public static void writeCachedRowSet() throws Exception{
	//Instantiate a CachedRowSet object, set connection parameters
	OracleCachedRowSet crs = new OracleCachedRowSet();
	Class.forName("oracle.jdbc.driver.OracleDriver");
	crs.setUrl("jdbc:oracle:thin:@localhost:1521:khan_db");
	crs.setUsername("scott");
	crs.setPassword("tiger");
	//Set and execute the command. Notice the parameter query.
	String sql = "SELECT SSN, Name, Salary, Hiredate ";
	sql = sql + "FROM Employees WHERE SSN=?";
	crs.setCommand(sql);
	crs.setInt(1,123456);
	crs.execute();
	//Serialize CachedRowSet object.
	FileOutputStream fos = new FileOutputStream(CRS_FILE_LOC);
	ObjectOutputStream out = new ObjectOutputStream(fos);
	out.writeObject(crs);
	out.close();
	crs.close();
}//end writeCachedRowSet()
 
public static OracleCachedRowSet readCachedRowSet() throws Exception{
	//Read serialized CachedRowSet object from storage
	FileInputStream fis = new FileInputStream(CRS_FILE_LOC);
	ObjectInputStream in = new ObjectInputStream(fis);
	OracleCachedRowSet crs = (OracleCachedRowSet)in.readObject();
	fis.close();
	in.close();
	return crs;
}//end readCachedRowSet()
 
}//end CachedRS
]]>
http://www.jdbctutorial.net/2011/10/oracle-cachedrowset-tutorial-with-jdbc/feed/ 0
Working with JdbcRowSet Object http://www.jdbctutorial.net/2011/10/working-with-jdbcrowset-object/ http://www.jdbctutorial.net/2011/10/working-with-jdbcrowset-object/#comments Thu, 20 Oct 2011 02:48:56 +0000 Tousif Khan http://www.jdbctutorial.net/?p=195 The JdbcRowSet class provides a basic implementation of the javax.sql.RowSet interface, which turns a ResultSet object into a JavaBean and abstracts the details of working with ResultSet objects. You can use this object to simplify connection steps or to provide scrollable and updateable cursors for drivers that do not support these features. However, JdbcRowSet objects can only operate in connected mode, thus requiring the presence of a JDBC driver.

Developing with RowSet objects requires a different approach than developing with the standard JDBC components. Actually, you may find it easier to develop with RowSet objects.

Setting RowSet Connection Property :
Unlike a ResultSet, a RowSet automatically connects to the data source when it needs to retrieve or update data. You do not need to explicitly call a connection method, as the object handles this task for you. The RowSet object’s ability to connect automatically is one of its benefits.

Following snippet illustrates how to configure the connection properties:

//Create JdbcRowSetObject
JdbcRowSet jrs = new JdbcRowSet();
//Load driver and set connection parameters
Class.forName("oracle.jdbc.driver.OracleDriver");
jrs.setUrl("jdbc:oracle:thin:@localhost:1521:khan_db");
jrs.setUsername("scott");
jrs.setPassword("tiger");

Executing SQL commands using JdbcRowSet:
You can execute both DDL and DML SQL statements using a RowSet object. However, because the RowSet object acts like a JavaBean, it need to be execute the statements differently from the way you execute them in standard JDBC programming.

One difference is that you do not need to instantiate Statement, PreparedStatement, or CallableStatement objects to execute SQL statements. The RowSet object manages the details of submitting the SQL command and handling the results. It determines whether you are submitting a parameterized query or calling a stored procedure, and acts accordingly.

//Instantiate a JdbcRowSet object
JdbcRowSet jrs = new JdbcRowSet();
//Load driver and set connection parameters
Class.forName("oracle.jdbc.driver.OracleDriver");
jrs.setUrl("jdbc:oracle:thin:@localhost:1521:khan_db");
jrs.setUsername("scott");
jrs.setPassword("tiger");
//Set and execute the command
String sql = "SELECT SSN, Name, Salary, Hiredate FROM Employees";
jrs.setCommand(sql);
jrs.execute();

Fetching data from a RowSet:
Once you have populated a rowset, you need to extract the data from the rowset before it. To do so you rely on an inherited RowSet.getXXX() methods; where the XXX refers to the Java data type of the variable into which you want to place the value.

Following is the code.


import java.sql.SQLException;
import oracle.jdbc.rowset.OracleJDBCRowSet;

public class JdbcRowSetDemo {
	public static void main(String[] args){
	try {

	//Instantiate a OracleJDBCRowSet object
	// OracleJDBCRowSet is a Oracle implementation
		OracleJDBCRowSet jrs = new OracleJDBCRowSet();
		//Load driver and set connection parameters
		Class.forName("oracle.jdbc.driver.OracleDriver");
		jrs.setUrl("jdbc:oracle:thin:@localhost:1521:khan_db");
		jrs.setUsername("scott");
		jrs.setPassword("tiger");
		//Set and execute the command
		String sql;
		sql = "SELECT SSN, Name, Salary, Hiredate FROM Employees";
		jrs.setCommand(sql);
		jrs.execute();
		//Display values
		while(jrs.next()){
			System.out.print("SSN: " + jrs.getInt("ssn"));
			System.out.print(", Name: " + jrs.getString("name"));
			System.out.print(", Salary: $" + jrs.getDouble("salary"));
			System.out.print(", HireDate: " + jrs.getDate("hiredate"));
			System.out.println();
		}
		//Close the resource
		jrs.close();
		}catch (SQLException se){
			se.printStackTrace();
		}catch (Exception ex) {
			ex.printStackTrace();
		}
	//Say goodbye
	System.out.println("Goodbye!");
	}//end main
}// end JdbcRowSetDemo
]]>
http://www.jdbctutorial.net/2011/10/working-with-jdbcrowset-object/feed/ 0
Reading Oracle Struct Object Using JDBC getObject() http://www.jdbctutorial.net/2011/10/reading-oracle-struct-object-using-jdbc-getobject/ http://www.jdbctutorial.net/2011/10/reading-oracle-struct-object-using-jdbc-getobject/#comments Thu, 20 Oct 2011 02:43:04 +0000 Tousif Khan http://www.jdbctutorial.net/?p=192 In Our last tutorial, Inserting Struct Object data Using JDBC i explain how to create a user-defined-type (Struct) using Oracle. We also see how to insert your own java object in that UDT. Now using the same tutorial, just we are going to see how you can read that UDT using PreparedStatement’s getObject() method.

To read that Object use java.sql.ResultSet interfaces getObject() method. Type cast that Object by using Struct type and call the Struct’s getAttributes() method. this method return array of Object (Object[]). Following is the code to read the Struct Object.

CREATE TYPE empaddress AS OBJECT (
	flatno NUMBER,
	street varchar2(20),
	city varchar2(15),
	state varchar2(10),
	pincode NUMBER
);
CREATE TABLE personal_details (
	empno NUMBER,
	photo BLOB,
	permanent_address empaddress,
	present_address empaddress
);

Following is the java code.

import java.sql.*;
import java.util.*;
import java.io.*;
 
public class GetEmployeeAddressUsingStruct {
 
	public static void main(String s[]) throws Exception {
	Driver d= (Driver) ( Class.forName( 
		"oracle.jdbc.driver.OracleDriver").newInstance());
	Properties p=new Properties ();
	p.put("user","scott");
	p.put("password","tiger");
	Connection con=d.connect("jdbc:oracle:thin:@mysys:1521:khan",p);
	Statement st=con.createStatement();
	ResultSet rs=st.executeQuery(
	"select permanent_address from personaldetails where empno="+s[0]);
	if (rs.next()){
		Struct struct=(Struct)rs.getObject(1);
		System.out.println("Employee Found: Address");
		Object addr[]=struct.getAttributes();
		System.out.println("Flatno : "+addr[0]);
		System.out.println("Street : "+ addr[1]);
		System.out.println("Pin    : "+addr[4]);
		}//if
		con.close();
	}//main
}//class
]]>
http://www.jdbctutorial.net/2011/10/reading-oracle-struct-object-using-jdbc-getobject/feed/ 0