[英]JDBC for SQLite in Netbeans: No suitable driver found
我需要将SQLite文件中的数据加载到我在Netbeans中开发的java程序中。 该文件将通过swing菜单项加载。 我正在使用sqlitejdbc作为驱动程序。
以下是我认为重要的代码块:
// 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)未加载驱动程序引起的。 以下是一些进一步的信息:
任何人都可以告诉我我在这里缺少什么吗? 任何帮助赞赏!
问题解决了以下代码对我有用:
//...
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中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.