我设置了代码,以便用户可以输入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();
}
感谢任何人提供的任何帮助,谢谢
答案 0 :(得分:0)
;newdatabaseversion=V2010
将创建一个新文件 at all 。如果它存在但包含零字节,则它不是有效的Access数据库。跟踪代码以查看它是否正在创建零字节文件,如果是,则在尝试打开连接之前删除该文件。