问题描述
Java教程说,有两种连接方法通过JDBC通过JDBC连接到数据库:使用 DriverManager 类(旧的,不推荐),并使用 DataSource 类.
Java Tutorial says there are 2 ways to connect to database thru JDBC: with DriverManager class (old, not recommended) and with DataSource class.
我不知道如何使用DriverManager:
I undestand how to do it with DriverManager:
Connection con = DriverManager.getConnection("jdbc:sqlite:mytest.db");
...
但是我找不到如何通过JDBC将DataSource用于SQLite. SQLite(或它的JDBC驱动程序提供者,我不知道如何正确调用)完全支持使用DataSource吗?
我正在使用 xerial/sqlite-jdbc 驱动程序从Java使用SQLite( https://github.com/xerial/sqlite-jdbc )
I am using xerial/sqlite-jdbc driver to use SQLite from java (https://github.com/xerial/sqlite-jdbc)
我的最佳猜测是,我将使用org.sqlite.SQLiteDataSource类(对于Xerial sqlite-jdbc驱动程序,它在sqlite-jdbc-3.15.1.jar中提供),但是如何?是这样吗?我还猜想,该如何做应该在Xerial驱动程序文档中进行,但它们仅给出了如何使用DriverManager进行连接的示例.
My best guess is that I shall use org.sqlite.SQLiteDataSource class (it comes in sqlite-jdbc-3.15.1.jar for Xerial sqlite-jdbc driver), but how? And is it so? I also guess, that how to do it shall be in Xerial driver docs, but they give only example of how to connect using DriverManager.
所以我要请教士提供帮助,以确认此 Xerial驱动程序/jar不支持DataSource语法,或者不提供示例操作方法,也不建议具有DataSource支持的替代驱动程序(适用于Java的SQLite),否则不提供建议...
So I am asking kind help of guru to confirm that this Xerial driver/jar doesn't support DataSource syntax, or to give example how to do it, or to suggest alternative driver with DataSource support (for SQLite from Java), or advice otherwise...
标准扩展程序包javax.naming和javax.sql可让您使用 向Java命名和目录注册的DataSource对象 Interface™(JNDI)命名服务,用于与数据建立连接 资源.您可以使用任何一种连接机制,但可以使用 建议尽可能使用DataSource对象.
The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a connection with a data source. You can use either connecting mechanism, but using a DataSource object is recommended whenever possible.
推荐答案
是的,这似乎很可能.
我只是尝试了以下方法,对我有用:
I just tried the following and it worked for me:
package com.example.sqlite.sqlite_test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.sqlite.SQLiteDataSource;
public class SqliteTestMain {
public static void main(String[] args) {
SQLiteDataSource ds = new SQLiteDataSource();
ds.setUrl("jdbc:sqlite::memory:");
try (Connection conn = ds.getConnection()) {
System.out.println("Connected.");
String sql =
"SELECT COUNT(*) AS n FROM \"sqlite_master\"";
try (
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery(sql)) {
rs.next();
System.out.printf(
"The \"sqlite_master\" table contains %d row(s).%n",
rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace(System.err);
}
}
}
这篇关于使用DataSource通过(Xerial)sqlite-jdbc驱动程序连接到SQLite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!