Utility Class For Getting SQL Connection and Closing It

The following is a sample class which you can use as an utility in getting the mysql connections
and closing it (rather than writing the same code again and again to get and close the connection)

/* @author Kushal Paudyal*/
package com.ghumti.kschool.core.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import com.ghumti.fw.domain.KSEntity;

public class KSDBConnection extends KSEntity {
	private String dbUserName = "root";
	private String dbPassword = "";
	private String dbURL = "jdbc:mysql://localhost:3306/";
	private String database = "kschool";
	private String driver = "com.mysql.jdbc.Driver";

	public Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(driver).newInstance();
			conn = DriverManager.getConnection(getDbURL() + getDatabase(),
					getDbUserName(), getDbPassword());

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return conn;
		}

	}

	public void closeConnection(Connection dbConnection, String className) {
		try {
			dbConnection.close();
		} catch (SQLException e1) {
			System.out.println(className
					+ ": Could not close database connection");
			e1.printStackTrace();
		}

	}

	/*
	 * Usage Example
	 */
	public static void main(String args[]) throws Exception {
		KSDBConnection ksdb = new KSDBConnection();
		Connection conn = ksdb.getConnection();

		String sqlQuery = "Select * from myTable";
		Statement st = conn.createStatement();
		st.execute(sqlQuery);

		/*
		 * Finally Close the connection The second parameter is just used for
		 * error printing
		 */
		ksdb.closeConnection(conn, KSDBConnection.class.getName());

	}

}

Share
Tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply