如何使用 JDBC 访问 Tomcat 中的 SQLite 数据库?抛出 UnsatisfiedLinkError

Posted

技术标签:

【中文标题】如何使用 JDBC 访问 Tomcat 中的 SQLite 数据库?抛出 UnsatisfiedLinkError【英文标题】:How to access SQLite database in Tomcat using JDBC? UnsatisfiedLinkError thrown 【发布时间】:2020-09-06 19:15:24 【问题描述】:

我正在使用 Servlet、JSP、JSTL 技术开发 Web Java 应用程序。我使用 SQLite3 数据库,在 IntelliJ Idea IDE 中开发,使用 Maven 编译项目并在 Tomcat 9.0 中进行测试。

我可以直接访问 SQLite 数据库(使用命令行和 sqlite3 下载库:screenshot)。

当我在 intellij idea 中运行 SQLite 数据库时,我还可以通过 JDBC 作为普通 JavaSE 应用程序访问它:screenshot。

但是当我在 Tomcat 上启动我的 web 项目时,在网页上 ServletException 被 UnsatisfiedLinkError 抛出:

HTTP Status 500 – Internal Server Error
Type Exception Report

Message Servlet execution threw an exception

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

javax.servlet.ServletException: Servlet execution threw an exception
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

java.lang.UnsatisfiedLinkError: 'void org.sqlite.core.NativeDB._open_utf8(byte[], int)'
    org.sqlite.core.NativeDB._open_utf8(Native Method)
    org.sqlite.core.NativeDB._open(NativeDB.java:71)
    org.sqlite.core.DB.open(DB.java:174)
    org.sqlite.core.CoreConnection.open(CoreConnection.java:220)
    org.sqlite.core.CoreConnection.<init>(CoreConnection.java:76)
    org.sqlite.jdbc3.JDBC3Connection.<init>(JDBC3Connection.java:25)
    org.sqlite.jdbc4.JDBC4Connection.<init>(JDBC4Connection.java:24)
    org.sqlite.SQLiteConnection.<init>(SQLiteConnection.java:45)
    org.sqlite.JDBC.createConnection(JDBC.java:114)
    org.sqlite.JDBC.connect(JDBC.java:88)
    org.apache.tomcat.dbcp.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:53)
    org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:355)
    org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:116)
    org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:731)
    org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:605)
    org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:809)
    model.DAO.getRooms(DAO.java:29)
    servlets.HomepageServlet.doGet(HomepageServlet.java:55)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.

在 tomcat 的 startup.bat 命令行窗口中,我看到:

06-Sep-2020 21:11:37.875 INFO [http-nio-8080-exec-32] org.apache.catalina.core.StandardContext.reload Reloading Context with name [/testProject_war_exploded] has started
06-Sep-2020 21:11:38.352 INFO [http-nio-8080-exec-32] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
06-Sep-2020 21:11:38.375 INFO [http-nio-8080-exec-32] org.apache.catalina.core.StandardContext.reload Reloading Context with name [/testProject_war_exploded] is completed
C:\Dropbox\apache-tomcat-9.0.22\temp\sqlite-3.21.0.1-02fa308c-7c4d-4cfb-93cb-3e46dbaa56a1-sqlitejdbc.dll.lck (Системе не удается найти указанный путь)

(系统找不到指定的路径)

这是抛出异常的方法:

package model;

import org.apache.log4j.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DAO 
    private final Logger log = Logger.getLogger(this.getClass());
    private final String driverName = "org.sqlite.JDBC";

    public List<Room> getRooms() 
        List<Room> rooms = new ArrayList<Room>();
        Connection connection = null;
        try 
            Class.forName(driverName);
            Context ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/rooms");
            connection = ds.getConnection();
         catch (ClassNotFoundException e) 
            log.debug("Can't get class. No driver found");
            e.printStackTrace();
         catch (SQLException e) 
            log.debug("Can't get connection. Incorrect URL");
            e.printStackTrace();
         catch (NamingException e) 
            log.debug("Can't get Context or Datasource");
            e.printStackTrace();
         catch (Exception e) 
            log.debug("Some other exception");
            e.printStackTrace();
        
        try 
            String sql = "SELECT * FROM room";
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            Room room;
            while (rs.next()) 
                room = new Room();
                room.setName(rs.getString("name"));
                room.setCountryCode(rs.getString("country_code"));
                room.setLightOn(rs.getInt("light_status"));
                rooms.add(room);
                log.debug(room.getName() + " " + room.getCountryCode() + "" + room.isLightOn());
            
         catch (SQLException e) 
            log.debug("SQL Exception thrown during select statement");
            e.printStackTrace();
        
        try 
            connection.close();
         catch (SQLException e) 
            log.debug("Can't close connection");
            e.printStackTrace();
        
        return rooms;
    

正是这一行在 Servlet 的异常中写为:model.DAO.getRooms(DAO.java:28)

connection = ds.getConnection();

但是,我在没有 Tomcat 的情况下用于 SQLite 访问检查的这段代码工作正常。 所以这让我觉得它完全在“tomcat方面”

import model.Room;
import org.apache.log4j.Logger;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Main 
    private final Logger log = Logger.getLogger(this.getClass());
    private final String driverName = "org.sqlite.JDBC";
    private final String connectionString = "jdbc:sqlite:rooms.db";

    public void run() 
        List<Room> rooms = new ArrayList<Room>();
        Connection connection = null;
        try 
            Class.forName(driverName);
            connection = DriverManager.getConnection(connectionString);
         catch (ClassNotFoundException e) 
            log.debug("Can't get class. No driver found");
            e.printStackTrace();
         catch (SQLException e) 
            log.debug("Can't get connection. Incorrect URL");
            e.printStackTrace();
        
        try 
            String sql = "SELECT * FROM room";
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            Room room;
            while (rs.next()) 
                room = new Room();
                room.setName(rs.getString("name"));
                room.setCountryCode(rs.getString("country_code"));
                room.setLightOn(rs.getInt("light_status"));
                rooms.add(room);
                System.out.println(room.getName() + " " + room.getCountryCode() + " " + room.isLightOn());
            
         catch (SQLException e) 
            log.debug("SQL Exception thrown during select statement");
            e.printStackTrace();
        
        try 
            connection.close();
         catch (SQLException e) 
            log.debug("Can't close connection");
            e.printStackTrace();
        
    
    public static void main(String[] args) 
        Main app = new Main();
        app.run();
    

为了让 Tomcat 找到我的数据库,我在 web.xml 中创建了资源引用

    <resource-ref>
        <description>Rooms Database</description>
        <res-ref-name>jdbc/rooms</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

并且还在 tomcat-dir\conf\Catalina\localhost\testProject_war_exploded.xml 中添加了 Context 标签 其中 testProject_war_exploded 是我的应用程序的名称。

<Context reloadable="true" antiJARLocking="true" path="/" docBase="C:\Users\nativ\IdeaProjects\testProject\out\artifacts\testProject_war_exploded\">
    <Resource name="jdbc/rooms"
      auth="Container"
      type="javax.sql.DataSource"
      driverClassName="org.sqlite.JDBC"
      url="jdbc:sqlite:rooms.db">
    </Resource>
</Context>

我也尝试使用相同的代码将具有相同 Context 标记的 context.xml 创建到 /META-INF/context.xml 中。

或者我尝试将 Context 标签添加到 tomcat-dir/conf/server.xml 中的 GlobalNamingResources 标签中 - 我知道不推荐这样做,但仍然没有结果。

我确信 tomcat 会找到该 rooms.db 文件,因为如果我更改路径 - 我会收到 SQLException 和“无法连接。不正确的 URL”写入我的日志文件。

我确定 tomcat 会加载 sqlite3 jar 库,因为我们从 org.sqlite.core 包中抛出了异常。

虽然我很困惑,为什么如果我捕捉到任何异常,我的日志文件中没有来自这个 getRooms() 方法的记录。但是如果我捕获(Throwable),那么我有一个日志文件记录 - 这意味着抛出了一个错误。

在 SQLite 文档中,我发现 a variable 告诉 sqlite 是使用临时文件夹还是内存。 我可以更改它via command line,但是 Tomcat 使用 sqlite3 jar 库来打开我的数据库。 我应该改变那个罐子里的东西吗?我不知道为什么 tomcat 中的 sqlite3 会尝试访问这个 /temp/... 文件夹。

This isidea 在 \out 目录中创建的我的 Web 项目结构。

这是我的 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>testProject</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.release>11</maven.compiler.release>
        <junit.jupiter.version>5.6.2</junit.jupiter.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/jstl/jstl -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>$junit.jupiter.version</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>$junit.jupiter.version</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>$junit.jupiter.version</version>
            <scope>test</scope>
        </dependency>
        <!-- API for countries' names and codes list -->
        <dependency>
            <groupId>com.neovisionaries</groupId>
            <artifactId>nv-i18n</artifactId>
            <version>1.22</version>
        </dependency>
        <dependency>
            <groupId>com.maxmind.geoip2</groupId>
            <artifactId>geoip2</artifactId>
            <version>2.14.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.21.0.1</version>
        </dependency>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <release>11</release>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <nonFilteredFileExtensions>
                        <nonFilteredFileExtension>exe</nonFilteredFileExtension>
                    </nonFilteredFileExtensions>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

以及处理索引页面的 Servlet 类。

package servlets;

import com.maxmind.geoip2.record.Country;
import com.neovisionaries.i18n.CountryCode;

import controller.LocationHelper;
import model.DAO;
import model.Room;
import org.apache.log4j.Logger;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class HomepageServlet extends HttpServlet 
    private LocationHelper locationHelper = new LocationHelper();
    private DAO dao = new DAO();
    private final Logger log = Logger.getLogger(this.getClass());

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        String roomName = request.getParameter("roomName");
        log.debug("roomName = " + roomName);

        String selectedCountry = request.getParameter("countryList");
        log.debug("selectedCountry = " + selectedCountry);

        doGet(request, response);
    

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");

        String ipStr = LocationHelper.getClientIpAddr(request);
        request.setAttribute("ipAddress", ipStr);

        String countryStr = "not determined";
        String countrycode = "no code";
        Country country = locationHelper.getCountry(getServletContext());
        if (country != null) 
            countryStr = country.getName();
            countrycode = country.getIsoCode();
        

        request.setAttribute("country", countryStr);
        request.setAttribute("code", countrycode);

        List<String> countries = getSortedCountriesList();
        request.setAttribute("countriesList", countries);

        List<Room> rooms = dao.getRooms();
        request.setAttribute("roomsList", rooms);

        requestDispatcher.forward(request, response);
    

    /**
     *
     * @return Sorted countries list to be shown in a dropdown list.
     */
    private List<String> getSortedCountriesList() 
        List<String> countriesList = new ArrayList<>();
        for (CountryCode code : CountryCode.values()) 
            countriesList.add(code.getName());
        

        Collections.sort(countriesList, (s1, s2) -> s1.compareToIgnoreCase(s2));
        return countriesList;
    


【问题讨论】:

connection = ds.getConnection(); 替换为connection = DriverManager.getConnection("jdbc:sqlite:rooms.db"); 会发生什么?如果 WEB-INF/lib 有驱动程序 jar,它应该可以工作。 jar 位于 WEB-INF/lib 文件夹中,但它仍然给了我同样的异常。我也将 sqilte jar 直接放入 tomcat/lib 文件夹,但关于 not found \temp\... 文件夹的消息仍然相同 【参考方案1】:

您很可能缺少 sqlite-jdbc 所需的本机库。

https://github.com/xerial/sqlite-jdbc/blob/master/src/main/java/org/sqlite/SQLiteJDBCLoader.java#L305

尝试为 jvm 提供 org.sqlite.lib.path 属性,指向 sqlite 共享库的位置。

【讨论】:

我将 sqlite jar 直接放入 tomcat/lib 文件夹中,在数据库访问代码编写 set 属性之前,如下所示:System.setProperty("org.sqlite.lib.path", "$catalina.home" + "/lib/sqlite-jdbc-3.21.0.1.jar"); 但是当我决定先看看这个属性是什么时,getProperty() 准确地给了我我正在设置的那个字符串。 Servlet 仍然抛出相同的错误,但启动 cmd 没有给出“未找到 /temp/... dir”。相反,它写了 failed to unregistration JDBC driver link 这是否意味着 JDBC driver 已注册,但由于抛出的错误而没有取消注册?【参考方案2】:

当在 IDE 根文件夹创建连接时,SQLite 将创建一个 DB 文件,要处理这个并指向您的目标 DB,只需使用其完整路径,步骤如下:

    将 sqlite-jdbc jar 文件放入 Tomcat\lib 文件夹中 将您的数据库文件 [MyDB.db OR MyDB.sqlite] 放入 Tomcat\lib 文件夹或创建另一个文件夹“db”并在创建 Connection 时使用其完整路径指向它 对象。

【讨论】:

以上是关于如何使用 JDBC 访问 Tomcat 中的 SQLite 数据库?抛出 UnsatisfiedLinkError的主要内容,如果未能解决你的问题,请参考以下文章

Tomcat/数据库设置 - JDBC 连接池

org.apache.tomcat.jdbc.pool 中的验证查询

Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: ..... this is incompatible with sq

前段时间,接手一个项目使用的是原始的jdbc作为数据库的访问,发布到服务器上在运行了一段时间之后总是会出现无法访问的情况,登录到服务器,查看tomcat日志发现总是报如下的错误。    Cause

Tomcat 中的 JDBC Pool

tomcat JDBC连接池c3p0连接资源耗尽导致tomcat实例对应的app移动端无法访问。