UCanAccess with JFileChooser: "Empty database file"



我设置了我的代码,以便用户可以输入Microsoft Access文件的名称,然后成功创建该文件。但是,我想使用 JFileChooser 使过程更顺畅,但是当我使用它时我的代码不起作用。

这是我(工作(以前的代码,剪掉了一些不相关的代码-

try {
    fileName = JOptionPane.showInputDialog(null,"Enter file name ");
   String dbPath = "C:/Users/Evan/Documents/"+fileName+".accdb";
       System.out.println(dbPath);
       // outputs C:/Users/Evan/Documents/fileName.accdb
try (Connection conn = DriverManager.getConnection(
    "jdbc:ucanaccess://" + dbPath  
 +   ";newdatabaseversion=V2010"
)) {
 DatabaseMetaData dmd = conn.getMetaData();
    try (ResultSet rs = dmd.getTables(null, null, "Database", new String[] { "TABLE" })) {
        try (Statement s = conn.createStatement()) {
            s.executeUpdate("CREATE TABLE " + "Database " 
+" (Row COUNTER PRIMARY KEY, A DOUBLE , B DOUBLE)");
            System.out.println("File " + fileName + " created.");
            valueProperty.setValue(fileName);
        }
}
conn.close();
 }
}
 catch (Exception f){
  f.printStackTrace();
 }
       }

这是我现在拥有的代码,它输出的错误

net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.2 空数据库文件

并生成一个不包含并包含错误消息"无法识别的数据库格式"以及文件的名称和路径的文件,尽管该文件的路径与其他工作文件相同,不包括文件名:

try {
    JFileChooser chooser = new JFileChooser();
   chooser.setCurrentDirectory(new File("/home/me/Documents"));
int retrieval = chooser.showSaveDialog(null);
if (retrieval == JFileChooser.APPROVE_OPTION) {
   FileWriter fw = new FileWriter(chooser.getSelectedFile()+".accdb");

  path=chooser.getSelectedFile().getAbsolutePath()+".accdb";
 // System.out.println(path);
fileName=chooser.getSelectedFile().getName();
   String dbPath = path.replace("\","/"); /* I know this looks weird, I
just did it because the output in the working version has it with / instead. 
I've tried it with both slashes and the result is the same. */   
   System.out.println(dbPath);
   // outputs C:/Users/Evan/Documents/fileName.accdb
/*where the code has an error */  try (Connection conn = DriverManager.getConnection(
    "jdbc:ucanaccess://" + dbPath  
 +   ";newdatabaseversion=V2010"
)) {
DatabaseMetaData dmd = conn.getMetaData();
    try (ResultSet rs = dmd.getTables(null, null, "Database", new String[] { 
"TABLE" })) {
        try (Statement s = conn.createStatement()) {
            s.executeUpdate("CREATE TABLE " + "Database" +" (Row COUNTER 
PRIMARY KEY, A DOUBLE , B DOUBLE)");
            System.out.println("File " + fileName + " created.");
            valueProperty.setValue(fileName);
        }
}
conn.close();
 }}
else 
    System.out.println("failed");
    return;
}
catch (Exception f){
  f.printStackTrace();
}

我将不胜感激任何人可以提供的任何帮助,谢谢

如果它根本不存在,;newdatabaseversion=V2010将创建一个新文件。如果它存在,但包含零字节,则它不是有效的 Access 数据库。跟踪代码以查看它是否正在创建零字节文件,如果是,请在尝试打开连接之前删除该文件。

最新更新