带有 JFileChooser 的 UCanAccess:“空数据库文件”
Posted
技术标签:
【中文标题】带有 JFileChooser 的 UCanAccess:“空数据库文件”【英文标题】:UCanAccess with JFileChooser: "Empty database file" 【发布时间】:2017-06-20 20:24:18 【问题描述】:我设置了我的代码,以便用户可以输入 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 数据库。跟踪您的代码以查看它是否正在创建零字节文件,如果是,则在尝试打开连接之前删除该文件。
我删除了FileWriter fw = new FileWriter(chooser.getSelectedFile()+".accdb");
行,现在它运行良好,你说得对,它制作了 0 个咬文件。谢谢!
【参考方案1】:
;newdatabaseversion=V2010
将创建一个新文件,如果它根本不存在。如果它存在,但包含零字节,则它不是有效的 Access 数据库。跟踪您的代码以查看它是否正在创建一个零字节文件,如果是,则在尝试打开您的连接之前删除该文件。
【讨论】:
以上是关于带有 JFileChooser 的 UCanAccess:“空数据库文件”的主要内容,如果未能解决你的问题,请参考以下文章
如何在 JFileChooser 中显示文件的默认系统图标?