1
我有我的代碼設置,以便用戶可以輸入一個Microsoft Access文件的名稱,然後該文件已成功創建。但是,我想使用JFileChooser使流程更加流暢,但是當我使用它時,我的代碼不起作用。UCanAccess與JFileChooser:「空數據庫文件」
這裏是我的(工作)以前的代碼,用一些不相干的代碼剪斷OUT-
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空數據庫文件
並生成一個文件,其中不包含錯誤消息「無法識別的數據庫f ORMAT」的名稱和文件的路徑,儘管該文件是相同的,這不包括文件名其他工作文件的路徑:
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數據庫。跟蹤您的代碼,看看它是否正在創建一個零字節文件,如果是,則在嘗試打開連接之前刪除該文件。 –
我刪除了'FileWriter fw = new FileWriter(chooser.getSelectedFile()+「.accdb」);'現在線程完全正常工作,您正確地使它成爲0咬文件。謝謝! – Evan