Wednesday, April 25, 2012

Create MDB (Access Database File) using Java

Required Jar (Click to Download)

Steps
  • Add all Jar file to your java project
  • use folllowing code
package net.yogesh.test;

import com.healthmarketscience.jackcess.ColumnBuilder;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
import com.healthmarketscience.jackcess.TableBuilder;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.Types;

/**
 *
 * @author yogesh.mpower
 */
public class java2mdb {

    private static Database createDatabase(String databaseName) throws IOException {
        return Database.create(new File(databaseName));
    }

    private static TableBuilder createTable(String tableName) {
        return new TableBuilder(tableName);
    }

    public static void addColumn(Database database, TableBuilder tableName, String columnName, Types sqlType) throws SQLException, IOException {
        tableName.addColumn(new ColumnBuilder(columnName).setSQLType(Types.INTEGER).toColumn()).toTable(database);
    }

    public static void createDB() throws IOException, SQLException {
        String databaseName = "D:/employeedb.mdb"; // Creating an MS Access database
        Database database = createDatabase(databaseName);

        String tableName = "EmployeeDetail"; // Creating table
        Table table = createTable(tableName)
                .addColumn(new ColumnBuilder("Emp_Id").setSQLType(Types.INTEGER).toColumn())
                .addColumn(new ColumnBuilder("Emp_Name").setSQLType(Types.VARCHAR).toColumn())
                .toTable(database);

        table.addRow(1, "yogesh");//Inserting values into the table
        table.addRow(2, "abc");
        table.addRow(3, "pqr");
    }

    public static void main(String[] args) throws IOException, SQLException {
        java2mdb.createDB();
    }
}
  

Output 

file created at path D:/employeedb.mdb
with data

 






 

No comments:

Post a Comment

Disqus for yogi's talk

comments powered by Disqus