Jackcess 2.x的更新:现在使用DatabaseBuilder创建(或打开)数据库,因此要创建一个新的数据库文件,我们这样做
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.V, new File(dbPath))) {
System.out.println("The database file has been created.");
} catch (IOException ioe) {
ioe.printStackTrace(System.err);
}
}
}
Jackcess 1.x的原始答案(已弃用):
如果您想通过java创建“.mdb”文件,可以使用Jackcess Java库,它是用于读取和写入MS Access数据库的纯Java库之一.目前支持的版本包括2000-我猜.请查看以下示例以便更好地理解:
>下载Jackcess Java库(jackcess-1.2.6.jar)
从/
和commons-logging-1.1.jar
从/logging/download_logging.cgi开始
和commons-lang-2.0.jar
从/index.x?query=commons-lang
>将两个罐子添加到类路径中.
>尝试以下代码自动创建数据库:
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数据库_使用Java创建Access数据库文件(.mdb或.accdb)》对你有帮助,请点赞、收藏,并留下你的观点哦!