Java Tutorial says there are 2 ways to connect to database thru JDBC: with DriverManager class (old, not recommended) and with DataSource class.
I undestand how to do it with DriverManager:
Connection con = DriverManager.getConnection("jdbc:sqlite:mytest.db");
...
But I cannot find how to use DataSource for SQLite thru JDBC. Does SQLite (or JDBC driver providers for it, I don't know how to call it correctly) support using DataSource at all?
I am using xerial/sqlite-jdbc driver to use SQLite from java (https://github.com/xerial/sqlite-jdbc)
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.
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...
Java Tutorial
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),
Yes, that seems likely.
but how?
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With