Creating Data Access Object (DAO) Design Pattern
Posted on: March 3, 2011 at 12:00 AM
Creating Data Access Object (DAO) Design Pattern

Creating Data Access Object (DAO) Design Pattern

Data Access Object is the import component of the design patter of java. It provides a technique to separating the object persistence and data access logic. All the basic data access code contains in  DAO and it provides a simple interface to access the data.

In DAO you need to create the Connection factory class. This class contains the code for getting connection to the database.

For Example-

public class ConnectionFactory {
	String driverName = "com.mysql.jdbc.Driver";
	String conUrl = "jdbc:mysql://";
	String dbUser = "root";
	String dbPwd = "root";

	private static ConnectionFactory connectionFactory = null;

	private ConnectionFactory() {
		try {
		} catch (ClassNotFoundException e) {

	public Connection getConnection()  {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(conUrl, dbUser, dbPwd);

		} catch (Exception e) {
		return conn;

	public static ConnectionFactory getInstance() {
		if (connectionFactory == null) {
			connectionFactory = new ConnectionFactory();
		return connectionFactory;

Then Write the operatios on the on the table in a seperate class

package net.roseindia.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import net.roseindia.model.FinalResultModel;
import net.roseindia.model.PaperResultModel;

public class FinalResultDAO {
	Connection connect;
	PreparedStatement pst;
	ResultSet rs;
	int rightAns = 0, wrongAns = 0;
	int counter = 0, i = 0;

	public Connection getConnection() {
		Connection con;
		con = ConnectionFactory.getInstance().getConnection();
		return con;

	public void selectedAns(PaperResultModel obPaperSubmitModel, String language) {
		connect = getConnection();
		String ansQuesQuery = "insert into result_info(username,quesno,selectopt,language) values(?,?,?,?)";
		try {
			pst = connect.prepareStatement(ansQuesQuery);
			pst.setString(1, obPaperSubmitModel.getUsername());
			pst.setString(2, obPaperSubmitModel.getQuesno());
			pst.setString(3, obPaperSubmitModel.getAnswer());
			pst.setString(4, obPaperSubmitModel.getLanguage());
			System.out.println("Paper Successfully inserted in database.");
		} catch (SQLException e) {
		} finally {
			try {
				if (rs != null) {
				if (pst != null) {
			} catch (Exception e) {

After writing the DAO class you can use in anywhere in you application by making an object of DAO class .
For example-
QuestionDAO obQuestionDAO = new QuestionDAO();
int i = obQuestionDAO.addQuestion(obQuestionModel);

Related Tags for Creating Data Access Object (DAO) Design Pattern: