Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Do Database Connectivity Using Java for MS-Access Database?

Database Connectivity in Java for MS-Access

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.
  • Blank Database

  • STEP 2: Create a table and insert data into the table.
  • Create Table

  • STEP 3: Save the table with a desired name (e.g., "student").
  • Save Table

  • STEP 4: Open Control Panel, select *Administrative Tools*, and then click on *Data Source (ODBC)* -> *System DSN*.
  • ODBC Data Source

  • STEP 5: Click *Add* to create a new DSN, select *Microsoft Access Driver (*.mdb, *.accdb)*, and click *Finish*.
  • Add Driver

  • STEP 6: Assign a name to your Data Source (e.g., "mydsn") and click *Select* to choose the MS-Access file.
  • Data Source Name

  • STEP 7: Select the Access database file and click *OK* to finish the setup.
  • DSN Finish

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());
    }
    }
    }