JDBC: Connectivity with Access without DSN (Data Source Name)


In previous blogs you learn 5 steps to connect with database for MySQL and Oracle.

Here we will focus on two ways to connect java application with the access database.

  1. Without DSN (Data Source Name)
  2. With DSN

Example to Connect Java Application with access without DSN
In this example, we are going to connect the java program with the access database. Here, we have created the login table in the access database. There is only one column in the table named name. Let’s get all the name of the login table.

import java.sql.*;
class Test{
public static void main(String ar[]){
 try{
  String database="student.mdb";
//Here database exists in the current directory   

   String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};
          DBQ=" + database + ";DriverID=22;READONLY=true";   

   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection c=DriverManager.getConnection(url);
   Statement st=c.createStatement();
   ResultSet rs=st.executeQuery("select * from login");   

   while(rs.next()){
    System.out.println(rs.getString(1));
   }   

}catch(Exception ee){System.out.println(ee);}   

}}

Example to Connect Java Application with access with DSN
Connectivity with type-1 driver is not considered good. To connect java application with type-1 driver, create DSN first, here we are assuming your dsn name is mydsn.

import java.sql.*;
class Test{
public static void main(String ar[]){
 try{
   String url="jdbc:odbc:mydsn";
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection c=DriverManager.getConnection(url);
   Statement st=c.createStatement();
   ResultSet rs=st.executeQuery("select * from login");   

   while(rs.next()){
    System.out.println(rs.getString(1));
   }   

}catch(Exception ee){System.out.println(ee);}   

}}

Here you have learned both the ways to access with or without DSN (Data Source Name).

See Also:

More on JDBC

Follow below links to know more on JDBC and solving JDBC issues :

JDBC Tutorial

JDBC Sample Code

JDBC Issues and Solutions

JDBC Interview Questions And Answers

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s