How to Do Database Connectivity Using Java for MS-Access Database?
Share
Condition for Database Connectivity Using Java for MS-Access
Description:
JDBC (Java Database Connectivity) is used for connecting Java applications to a variety of databases, including Microsoft Access. To connect Java with MS-Access, you can use the JDBC-ODBC bridge or a third-party driver like UCanAccess. This process involves loading the necessary JDBC driver, setting up an ODBC Data Source Name (DSN), and then using the DriverManager to establish a connection and execute SQL queries. This allows your Java program to interact with an MS-Access database (.mdb or .accdb files) to fetch or manipulate data.
Steps for Database Connectivity
STEP 1: Open Microsoft Access, select *Blank database*, and provide a name for the database.
STEP 2: Create a table and insert data into the table.
STEP 3: Save the table with a desired name (e.g., "student").
STEP 4: Open Control Panel, select *Administrative Tools*, and then click on *Data Source (ODBC)* -> *System DSN*.
STEP 5: Click *Add* to create a new DSN, select *Microsoft Access Driver (*.mdb, *.accdb)*, and click *Finish*.
STEP 6: Assign a name to your Data Source (e.g., "mydsn") and click *Select* to choose the MS-Access file.
STEP 7: Select the Access database file and click *OK* to finish the setup.
Sample Source Code
# MsAcessODBC.java
import java.sql.*;
public class MsAcessODBC {
public static void main(String[] args) {
try {
// loading the JDBC ODBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// creating connection to the database
Connection con = DriverManager.getConnection("jdbc:odbc:mydsn", "", "");
Statement st = con.createStatement();
// create and execute an SQL query
ResultSet rs = st.executeQuery("SELECT * FROM student ORDER BY rollno ASC");
ResultSetMetaData rsmd = rs.getMetaData();
// get the number of columns in the selected table
int numberOfColumns = rsmd.getColumnCount();
// loop to print data from the result set
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1)
System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue);
}
System.out.println("");
}
st.close();
con.close();
} catch (Exception ex) {
System.err.print("Exception: ");
System.err.println(ex.getMessage());
}
}
}