Windows下java.sql.DriverManager数据库访问触发读取访问违例
问题:Windows打包后Java应用数据库操作崩溃(访问违例)
环境与打包信息
- 系统:Windows 11
- 终端环境:Visual Studio的vcvars64
- 打包命令:
gradle clean jlink --info gradle jpackage -PinstallerType=msi
现象
终端直接运行应用无任何报错,但启动打包后的.exe文件时,部分数据库操作(尤其是插入操作)会崩溃。使用Visual Studio调试时,每次数据库访问都会触发以下错误:
Exception thrown at 0x000001FE3BCBF1B1 in CharacterCreator.exe: 0xC0000005: Access violation reading location 0x0000000000000008
数据库连接代码
public ConnectionDB() { try { System.out.print("Connecting to the database... "); this.co = DriverManager.getConnection(DB_CONN_URL, DB_USER, DB_PASSWD); System.out.println("Connected"); } catch (SQLException e) { System.err.println("Failed"); e.printStackTrace(System.err); } } public Connection getCo() { return co; } public void close() { try { // Fermeture de la connection System.out.print("Disconnecting from the database... "); this.co.close(); System.out.println("disconnected"); } catch (SQLException e) { System.err.println("failed"); e.printStackTrace(System.err); } } public ResultSet executeQuery(String query) { // System.out.println(query); try { Statement statement = co.createStatement(); ResultSet result = statement.executeQuery(query); return result; } catch (SQLException e) { e.printStackTrace(); System.out.println(e.getMessage()); System.out.println(e.getErrorCode()); } return null; }
排查建议
- 检查JDBC驱动兼容性:确认驱动版本与jlink使用的JDK版本匹配,且是针对x64平台的版本。打包时可能遗漏了驱动的native依赖库,导致运行时底层调用出错。
- 验证打包依赖完整性:用
jlink --list-modules检查生成的运行时镜像是否包含JDBC驱动模块;查看打包后的应用目录,确认驱动的native库(如.dll)是否存在于正确路径。 - 修复连接对象生命周期问题:
- 修改
close()方法,关闭连接后将co置为null,避免后续代码误用已关闭的连接:public void close() { try { System.out.print("Disconnecting from the database... "); if (this.co != null && !this.co.isClosed()) { this.co.close(); this.co = null; } System.out.println("disconnected"); } catch (SQLException e) { System.err.println("failed"); e.printStackTrace(System.err); } } - 检查插入操作是否存在多线程共享同一个连接的情况,JDBC连接并非线程安全,多线程操作会导致底层资源混乱。
- 修改
- 启用调试日志:添加JDBC驱动的调试日志,或在JVM启动参数中加入
-Xcheck:jni,强制检查JNI调用合法性,定位native层错误来源。 - 测试极简场景:编写仅包含数据库插入的测试程序,用相同命令打包测试。若仍报错,聚焦依赖、驱动、打包配置;若正常,排查原应用中的资源泄漏或其他代码干扰问题。
内容的提问来源于stack exchange,提问作者Vincent
相关产品推荐
相关产品推荐

