Written by Sai Sandeep Thota on November 21, 2013 in How to > Java > Programming

How to Connect to Microsoft Access Database using Java JDBC

GET ALERTS:

Get our Latest updates delivered to your mailbox!

In this tutorial we are Connecting to Microsoft Access Database and retrieving records from it using Java. To connect to a Database we need to specify protocol:sub-protocol:data source. Protocol and Sub-protocol values are jdbc and odbc, we need to specify data source. In this tutorial we have created a Data source called myStore, so URL will look like: jdbc:odbc:myStore.

How to Connect to Microsoft Access Database using Java

In-order to connect to a Microsoft Access Database, you will need to specify the Data Source name in ODBC Data Sources which is located in Administrative Tools. So how to specify the Data Source?

#0. Create an Access Database.
#1. Go to Control Panel > Administrative Tools.
#2. Navigate to ODBC Data Sources.
#3. Add a New Data Source by Selecting Driver do Microsoft Access (*.mdb) as we are using Microsoft Access in this case.
#4. Specify Data Source Name and its path.
You can refer to the video tutorial below.

ODBC-Microsfot-Access-Setup

Java Program to Connect to Access Database

We have defined a ResultSet object called rs to store the results, url to specify protocol, sub-protocol and data source name.

forName method is used to specify drivers. We have defined Connection class object called con and we are establishing connection using DriverManager class, method getConnection(arg1, arg2, arg3). We have defined Statement class object stat and creating a statement using Connection class, executeQuery() method and getting the Query result to the ResultSet object rs.

We are using a while loop to fetch all the records from the Database Table. getString(2) specifies that we want to get the data from second Column.

import java.sql.*;

public class myStoreDemo {
	public static void main(String args[])
	{
		ResultSet rs;
		String url = "jdbc:odbc:myStore";
		String username = "";
		String password = "";

		try
		{

			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
	
			Connection con;
	
			con = DriverManager.getConnection(url, username, password);
		
			Statement stat;

			stat = con.createStatement();

			rs = stat.executeQuery("SELECT * FROM products");

			while(rs.next())
			{
				String row = rs.getString(2) + " Rs. " + rs.getString(3);
				System.out.println(row);
			}
		}
	
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}
		

retrieve-records-java

Download Source Code

Video

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: