How to get Database Connection using JDBC-ODBC?

DeeKay May 9, 2011 at 2:13 pm · java.sql

Below Java code shows how to get database connection using JDBC-ODBC :

/****************************************************************************************
 * Created on 05-2011 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javasql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by http://kodehelp.com
 * Date: 5/9/11
 */
public class GetJDBCODBCConnection {
    public static void main(String args[]) throws ClassNotFoundException, SQLException {
        Connection conn =null;
        ResultSet rs = null;
        try{
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        conn = DriverManager.getConnection(
                "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/access.mdb");
        rs = conn.createStatement().executeQuery("select empId,empName from Employee");

        while (rs.next()) {
          System.out.println(rs.getString("empId")+":"+rs.getString("empName"));
        }
        }catch (ClassNotFoundException cnfEx){
            throw cnfEx;
        }catch (SQLException sqlEx){
            throw sqlEx;
        }finally{
            if(rs!=null){
                rs.close();
            }
            if(conn!=null){
                conn.close();
            }
        }
    }
}