I have the following structure:
BUILD.bazel
MODULE.bazel
com/test/TestMain.java
com/test/assets/
Build.bazel
load("@rules_java//java:defs.bzl", "java_binary")
package(default_visibility = ["//visibility:public"])
java_binary(
name = "TestMain",
srcs = glob(["com/test/TestMain.java"]),
main_class = "com.test.TestMain",
resources = glob(["com/test/assets/*"])
)
Module.bazel
bazel_dep(name = "rules_java", version = "7.11.1")
bazel_dep(name = "sqlite3", version = "3.47.2")
com/test/TestMain.java
import java.io.IOException;
import java.sql.*;
public class TestMain {
public static void main(String args[]) throws IOException {
try {
Connection connection = DriverManager.getConnection("jdbc:sqlite:com/test/assets/sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30);
statement.executeUpdate("drop table if exists blog_post");
statement.executeUpdate("create table blog_post(id integer, title string, content string)");
statement.executeUpdate("insert into blog_post(1, 'test','ldsjkfslkdfjl')");
statement.executeUpdate("insert into blog_post(2, 'testdd','ldsjkfslkdfjl')");
ResultSet rs = statement.executeQuery("select * from blog_post");
while(rs.next()) {
System.out.println("title = " + rs.getString("title"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Which gives me
java.sql.SQLException: No suitable driver found for jdbc:sqlite:com/test/assets/sample.db
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:251)
Any ideas how I can get the driver to work?
At first I thought to add deps to the binary but I'm not sure how; I tried;
deps = ["sqlite3"]
which gives me
in deps attribute of java_binary rule //:TestMain: target '//:sqlite3' does not exist.
Changing the deps to
deps = ["@sqlite3"]
builds but the same no suitable driver error appears.
I tried adding a repo name to the bazel_dep
bazel_dep(name = "sqlite3", version = "3.47.2",
repo_name = "com_github_xerial_sqlite_jdbc")
and having it match the deps;
deps = ["@com_github_xerial_sqlite_jdbc//:sqlite3"]
As seen in the bazelbuild examples;
https://github.com/bazelbuild/examples/blob/main/bzlmod/01-depend_on_bazel_module/MODULE.bazel
https://github.com/bazelbuild/examples/blob/main/bzlmod/01-depend_on_bazel_module/BUILD
with the same issues.
you need to add the jar classpath, it has all the classes that are needed to access sqlite. JDBC is one of the most common ones, here’s an example of initiating with it:
Class.forName("org.sqlite.JDBC");
in case you need to download it here’s the github