【发布时间】:2021-05-28 03:19:17
【问题描述】:
我试图让 Xerial 的 Sample 类在 Eclipse 中使用 sqlite 工作,但我不断收到错误“ClassNotFoundException: org.sqlite.JDBC”
我从https://bitbucket.org/xerial/sqlite-jdbc/downloads 下载了 sqlite-jdbc-3.7.2.jar 文件。在eclipse中将它复制到我的项目“database_test”下的lib文件夹中。然后右击Project->Properties->Java Build Path->Libraries Tab->Add JARs->选择jar文件。我正在尝试从此处找到的 Xerial 执行此代码:https://bitbucket.org/xerial/sqlite-jdbc#markdown-header-usage
// load the sqlite-JDBC driver using the current class loader
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
statement.executeUpdate("drop table if exists person");
statement.executeUpdate("create table person (id integer, name string)");
statement.executeUpdate("insert into person values(1, 'leo')");
statement.executeUpdate("insert into person values(2, 'yui')");
ResultSet rs = statement.executeQuery("select * from person");
while(rs.next())
{
// read the result set
System.out.println("name = " + rs.getString("name"));
System.out.println("id = " + rs.getInt("id"));
}
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
} }
我去过的每个网站都说将 jar 文件添加到您的构建路径或类路径中,我相信我已经做到了,但没有任何解决问题的方法。任何帮助,将不胜感激。谢谢。
【问题讨论】:
-
假设您使用的是 Eclipse 或 Netbeans - 如果
DriverManager.getConnection()没有红色下划线(未找到类/方法)并且程序编译正常,那么它(几乎)可以安全地假设您正确导入 * .jar 文件。您可以尝试在左侧的 Files/Projects 窗口中展开libs文件夹,然后挖掘到sqlite-jdbc-3.7.2.jar-文件并查看org->sqlite->JDBC存在。 -
感谢您的回复。我正在使用 Eclipse,我打开了从 Xerial 下载的 jar 文件,文件夹结构 org/sqlite/JDBC.class 和 org/sqlite/JDBC.java 都存在于 JAR 文件中。运行 javac Sample.java 不会返回错误。 Eclipse 中也没有任何红色下划线...
-
您是在 IDE 中运行程序还是将其编译为
.jar并通过控制台运行?编辑:我还记得 Eclipse 也为您提供Add external JARs(虽然我有一段时间没有使用 Eclipse)-您也可以尝试一下,它应该使用库的完整路径而不是项目根目录的相对路径目录。 -
我也尝试了“添加外部 JAR”。我可能正在错误地编译/运行它。我首先尝试简单地在控制台上运行它: javac Sample.java -> java Sample... 并导致错误。在 Eclipse 中运行它只会导致 Eclipse 中的控制台窗口显示“
SQLite Java Application”。除了将 JAR 文件复制到我的 lib 文件夹并将其添加到构建路径之外,我是否需要对 JAR 文件执行其他任何操作? -
当您使用
javac将Sample.java编译成Sample.class时,您必须确保包含sqlite-jdbc-3.7.2.jar的lib路径相对于Sample.class。尝试创建一个文件夹"MyProgram",将Sample.class放入该文件夹和包含sql-connector 的lib文件夹;你应该有类似MyProgram/Sample.class和MyProgram/lib/sqlite-jdbc-3.7.2.jar的东西。然后尝试通过控制台运行它。