使用Java创建Access数据库文件(.mdb或.accdb) [英] Create an Access database file (.mdb or .accdb) using Java

查看:2924
本文介绍了使用Java创建Access数据库文件(.mdb或.accdb)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我有一个应用程序,我可以访问.mdb或.accdb
文件与JdbcOdbcDriver附加一些数据。

  Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); 
con = DriverManager.getConnection(jdbc:odbc:MsAccessDSN);

但在这里,我需要配置系统DSN。我们需要添加新的数据源(Microsoft Access驱动程序),然后需要提供.mdb文件的位置。只有那么上面的代码将工作。



假设我想在其他系统上运行我的应用程序,那么我需要做同样的事情到那台计算机。
如果我把我的应用程序给客户端,他/她不知道如何配置.mdb文件。然后我的整个努力会浪费。
所以任何驱动程序可用,我通过我的Java代码创建.mdb文件,然后将所有数据附加到.mdb文件的表中。
或者有其他方法,其中Java代码可以创建.mdb文件并且能够访问这个数据库文件。



我试过这个代码,配置系统DNS:

  public class TestMsAccess {

private static Connection con;
private static语句stm;
private static String tableName =EmpDetail;
private static int id_is = 2;
private static String name_is =Employee1;

public static void main(String [] args)throws ClassNotFoundException,SQLException {
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
con = DriverManager.getConnection(jdbc:odbc:Driver = {Microsoft Access Driver(* .mdb)}; DBQ = D:\\MSAccessProject / Employee.mdb,,);

stm = con.createStatement();
//在表中输入值
String addRow =INSERT INTO+ tableName +VALUES(
+ id_is +,'
+ name_is +' ;
stm.execute(addRow);

if(con!= null){con.close(); }
if(stm!= null){stm.close(); }
}

}

但问题是,代码不会自动创建.mdb文件,但在运行此代码之前创建.mbd文件和表时会工作。

解决方案

2.x:现在使用 DatabaseBuilder 创建(或打开)数据库,以便创建一个新的数据库文件



< pre class =lang-java prettyprint-override> import java.io.File;
import java.io.IOException;

import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Database.FileFormat;
import com.healthmarketscience.jackcess.DatabaseBuilder;

public class JackcessDemoMain {

public static void main(String [] args){
String dbPath =C:/Users/Public/newDb.accdb ;
//使用try-with-resources建议确保
//数据库对象正确关闭
try(Database db = DatabaseBuilder.create(FileFormat.V2010,new File dbPath))){
System.out.println(数据库文件已创建。
} catch(IOException ioe){
ioe.printStackTrace(System.err);
}

}

}



< hr>

Jackcess 1.x的原始回答(已弃用):



要通过java创建.mdb文件,可以使用Jackcess Java库,它是用于读取和写入MS Access数据库的纯Java库之一。目前支持版本包括2000-2007我猜。请查看下面的示例以便更好地了解:


  1. 下载Jackcess Java库(jackcess-1.2.6.jar)
    来自 http://jackcess.sourceforge.net/
    和commons-logging-1.1。 jar
    来自 http://commons.apache.org/logging/download_logging.cgi
    和commons-lang-2.0.jar
    来自 http://www.findjar.com/index.x?query=commons-lang

  2. 将两个jars添加到类路径。

  3. 尝试以下代码自动创建数据库:






  package com.jackcess.lib; 


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 sarath_ivan
* /
public class JackcessLibrary {

private static数据库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 startDatabaseProcess()throws IOException,SQLException {
String databaseName =C:/Users/compaq/Desktop/employeedb.mdb; //创建MS Access数据库
数据库数据库= createDatabase(databaseName);

String tableName =Employee; //创建表
表table = createTable(tableName)
.addColumn(new ColumnBuilder(Emp_Id)。setSQLType(Types.INTEGER).toColumn())
.addColumn(new ColumnBuilder (Emp_Name)。setSQLType(Types.VARCHAR).toColumn())
.addColumn(new ColumnBuilder(Emp_Employer)。setSQLType(Types.VARCHAR).toColumn())
.toTable数据库);

table.addRow(122875,Sarath Kumar Sivan,Infosys Limited。); //在表中插入值
}

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


Currently I have one application in which I am able to access .mdb or .accdb file with JdbcOdbcDriver to append some data.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con = DriverManager.getConnection("jdbc:odbc:MsAccessDSN");

but in this, I need to configure System DSN. We need to add new Data Source (Microsoft Access Driver) and then need to provide location of .mdb file. Only then above code will work.

Suppose I want to run my application on other system then I need to do same thing to that computer. If I give my application to the client and he/she don't know how to configure .mdb file. Then my whole effort will waste. So any driver is available by which I create .mdb file by my Java Code and then append all the data into the table of .mdb file. Or is there any other way, where Java code can create .mdb file and able to access this database file.

I tried this code which append data without configuring System DNS:

public class TestMsAccess {

private static Connection con;
private static Statement stm;
private static String tableName = "EmpDetail";
private static int id_is = 2;
private static String name_is = "Employee1";

public static void main(String[] args) throws ClassNotFoundException, SQLException {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=D:\\MSAccessProject/Employee.mdb", "", "");

    stm = con.createStatement();
    // enter value into table
     String addRow = "INSERT INTO " + tableName  + " VALUES ( "
        + id_is + ", '" 
        + name_is + "')";
     stm.execute(addRow);

     if (con != null) { con.close(); }
     if (stm != null) { stm.close(); }
}

}

But the problem is, this code not create .mdb file automatically but work when I create .mbd file and table before running this code.

解决方案

Update for Jackcess 2.x: Databases are now created (or opened) using DatabaseBuilder, so to create a new database file we do

import java.io.File;
import java.io.IOException;

import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Database.FileFormat;
import com.healthmarketscience.jackcess.DatabaseBuilder;

public class JackcessDemoMain {

    public static void main(String[] args) {
        String dbPath = "C:/Users/Public/newDb.accdb";
        // using try-with-resources is recommended to ensure that 
        //   the Database object will be closed properly
        try (Database db = DatabaseBuilder.create(FileFormat.V2010, new File(dbPath))) {
            System.out.println("The database file has been created.");
        } catch (IOException ioe) {
            ioe.printStackTrace(System.err);
        }

    }

}


Original answer for Jackcess 1.x (deprecated):

If you would like to create the ".mdb" file through java, you can use the Jackcess Java library which is one of the pure Java Library for reading from and writing to MS Access databases. Currently supporting versions include 2000-2007 I guess. Please have a look at the below example for better understanding:

  1. Download Jackcess Java library (jackcess-1.2.6.jar) from http://jackcess.sourceforge.net/ and commons-logging-1.1.jar from http://commons.apache.org/logging/download_logging.cgi and commons-lang-2.0.jar from http://www.findjar.com/index.x?query=commons-lang
  2. Add both jars to your classpath.
  3. Try the below code to create a database automatically:


package com.jackcess.lib;


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 sarath_ivan
 */
public class JackcessLibrary {

    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 startDatabaseProcess() throws IOException, SQLException {
        String databaseName = "C:/Users/compaq/Desktop/employeedb.mdb"; // Creating an MS Access database
        Database database = createDatabase(databaseName);

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

        table.addRow(122875, "Sarath Kumar Sivan","Infosys Limited.");//Inserting values into the table
    }

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

这篇关于使用Java创建Access数据库文件(.mdb或.accdb)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆