- 1. 在ClassPath下存一个空的blank.mdb. (也就是在你的项目中包含一个空白的.mdb文件)
- 2. 将项目中的blank.mdb另存到新的路径. (可能是用户选择要导出mdb文件的保存路径)
- 3. 将.mdb作为数据源, 用JDBC ODBC添加数据. 注: jdbc-odbc 在jre中是有的jre/lib/rt.jar. 也就是不需要引入额外的jar包.
注:
- 步骤3中, 你可以执行CREATE Table的SQL语句.
- 如果你已经知道了DB的SCHEMA, 那更简单了, 你直接在你的项目中包含一个带有SCHEMA的空的.mdb文件, 这样在步骤3的时候, 不需要再做表结构的创建, 只需要做数据插入即可.
public class AccessUtil { private Connection connection; private Statement statement; // 空白mdb文件路径. 直接保存在src/cn/iwoo/dataexport/common/下. private final String blankMdbFilePath = "cn/iwoo/dataexport/common/"; // 空白mdb文件名 private final String blankMdbFileName = "blank.mdb"; // 需要保存到的新的mdb文件路径和名 private String savedMdbFilePathAndName = defaultSavedMdbFilePath + defaultSavedMdbFileName; // 新mdb文件路径 public static final String defaultSavedMdbFilePath = "C://"; // 新mdb文件名 public static final String defaultSavedMdbFileName = "data.mdb"; // mdb文件后缀 public static final String defaultSavedMdbFileExtension = ".mdb"; // 标准的单件模式 private static AccessUtil instance = new AccessUtil(); private AccessUtil() { } public static AccessUtil getInstance() { return instance; } /** * <p>Description: 设置待保存的新的mdb文件路径和名</p> */ public void setSavedFilePathAndName(String newFilePathAndName) { this.savedMdbFilePathAndName = newFilePathAndName; } /** * <p>Description: 删除已经存在的mdb文件</p> */ public void deleteOldMdbFile() throws Exception { File oldTargetFile = new File(savedMdbFilePathAndName); if (oldTargetFile.exists()) { oldTargetFile.delete(); } } /** * <p>Description: 将空白mdb文件拷贝到特定目录</p> */ public void copyBlankMdbFile() throws Exception { InputStream is = this.getClass().getClassLoader().getResourceAsStream(blankMdbFilePath + blankMdbFileName); OutputStream out = new FileOutputStream(savedMdbFilePathAndName); byte[] buffer = new byte[1024]; int numRead; while ((numRead = is.read(buffer)) != -1) { out.write(buffer, 0, numRead); } is.close(); out.close(); } /** * <p>Description: 打开对mdb文件的jdbc-odbc连接</p> */ public void connetAccessDB() throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + savedMdbFilePathAndName.trim() + ";DriverID=22;READONLY=true}"; connection = DriverManager.getConnection(database, "", ""); statement = connection.createStatement(); } /** * <p>Description: 执行特定sql语句</p> */ private void executeSql(String sql) throws Exception { statement.execute(sql); } /** * <p>Description: 关闭连接</p> */ public void closeConnection() throws Exception { statement.close(); connection.close(); } }