Java Tutorial表示有两种方法可以通过JDBC连接到数据库:使用DriverManager类(旧的,不推荐使用)和使用DataSource类.
我不知道如何使用DriverManager做到这一点:
Connection con = DriverManager.getConnection("jdbc:sqlite:mytest.db");
...
但我找不到如何通过JDBC使用DataSource for sqlite. sqlite(或JDBC驱动程序提供程序,我不知道如何正确调用它)支持使用DataSource吗?
我正在使用xerial/sqlite-jdbc驱动程序从java中使用sqlite(https://github.com/xerial/sqlite-jdbc)
我最好的猜测是我将使用org.sqlite.sqliteDataSource类(它来自sqlite-jdbc-3.15.1.jar用于Xerial sqlite-jdbc驱动程序),但是怎么样?是这样吗?我也猜测,如何做到这一点应该是在Xerial驱动程序文档中,但它们只给出了如何使用DriverManager进行连接的示例.
所以我要求大师的帮助确认this Xerial驱动程序/ jar不支持DataSource语法,或者举例说明如何操作,或者建议使用DataSource支持替代驱动程序(对于sqlite来自Java),或者建议否则…
JDBC Driver Manager — The JDBC DriverManager class defines objects
which can connect Java applications to a JDBC driver. DriverManager
has traditionally been the backbone of the JDBC architecture. It is
quite small and simple.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.
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?
我只是尝试了以下内容,它对我有用:
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);
}
}
}