我需要将 SQLite 文件中的数据加载到我在 Netbeans 中开发的 java 程序中。
该文件将通过摆动菜单项加载。我在用着SQLitejdbc https://bitbucket.org/xerial/sqlite-jdbc/downloads#tag-downloads作为司机。
以下是我认为重要的代码块:
// header stuff
package aufgabe_9;
import java.sql.*;
//...
// menu item opening the file
private void mitemOpenFileActionPerformed(java.awt.event.ActionEvent evt)
{
/**
* Handles the dialogue for selecting and loading file.
*/
JFileChooser fileChoose = new JFileChooser();
fileChoose.showOpenDialog(this); //'this' calls the current object
//Load the sql file
try {
String filePath = fileChoose.getSelectedFile().toString();
Connection conn = DriverManager.getConnection("jdbc:sqlite:" +
filePath);
//Close the connection
if (conn != null)
conn.close();
}
catch (SQLException e){System.err.println("Database problem: " + e);}
}
}
//...
运行程序并通过菜单加载文件时,出现以下错误:
java.sql.SQLException: No suitable driver found for jdbc:sqlite:/home/levent
/temp/A9AProbeflaeche.db
阅读了相应的 stackexchange 帖子后,我明白了这一点
问题可能是由 (1) 文件 URL 格式错误或 (2) 驱动程序未安装引起的
已加载。以下是一些进一步的信息:
- 我通过以下方式将 sqlitejdbc-3.7.2.jar 添加到库类路径中工具 --> 库以及项目库通过窗口 --> 项目.
- 我还检查了类路径通过使用这个功能 http://www.mkyong.com/java/how-to-print-out-the-current-project-classpath/。正如预期的那样,它包含 jdbc jar 文件的路径。
- 我可以通过以下方式连接到数据库Services菜单没有任何问题,所以我可以假设 URL 是正确的,并且 sqlite 在我的系统上运行。
- 一些操作系统信息:我在 64 位 ARCH Linux 3.12.9-2 上运行 Netbeans 8.0。
有人能告诉我我在这里缺少什么吗?任何帮助表示赞赏!
问题解决了这是适合我的代码:
//...
private void mitemOpenFileActionPerformed(java.awt.event.ActionEvent evt)
{
/**
* Handles the dialogue for selecting and loading file.
*/
JFileChooser fileChoose = new JFileChooser();
fileChoose.showOpenDialog(this);
//Load the sql file
try {
//Get file path
String filePath = fileChoose.getSelectedFile().toString();
//Open connection
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + filePath);
//Do stuff...
//Close the connection
conn.close();
}
//"Multicatch":
catch (SQLException | ClassNotFoundException e) {
System.err.println("Database problem: " + e);
}
//...
您可能需要加载驱动程序类,以便它使用以下代码将自身注册到 DriverManager:
Class.forName("org.sqlite.JDBC");
注意:这只需要在您的应用程序中调用一次。
这是 Java 包含 ServiceLoader API 之前的标准过程,现在 DriverManager 使用该 API 来注册它在类路径中找到的驱动程序,但驱动程序需要声明一个名为 java.sql.Driver 的文件,其中包含驱动程序类的名称在其 jar 的 META-INF\services 目录中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)