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

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

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

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

当我以intellij想法screenshot运行它时,我也可以通过JDBC作为普通的JavaSE应用程序访问SQLite数据库。

但是,当我在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

    <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>

,还将Context标签添加到tomcat-dir \ conf \ Catalina \ localhost \ testProject_war_exploded.xml中 其中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.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 is我的网络项目结构,该构想是在\ out目录中创建的。

这是我的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,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;
    }

}

解决方法

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-