jruby java.sql.DriverManager 有问题吗?找不到适合 jdbc 的驱动程序:mysql://localhost/mydatabase

问题描述 投票:0回答:0

我正在尝试更新 jruby 应用程序

来自 java 1.8

Java 11.

无法获得一个简单的 jruby 程序来建立连接。我用 java 编写了相同的程序,它连接得很好,所以我知道问题出在 jruby 中。

require 'java'
require 'jdbc/mysql'

# Load the JDBC driver class

Jdbc::MySQL.load_driver
jdbc-mysql

# Set up the JDBC connection parameters

url = "jdbc:mysql://localhost/mydatabase?user=root"

# Connect to the database
conn = java.sql.DriverManager.get_connection(url)`
irb(main):027:0> conn = java.sql.DriverManager.get_connection(url)
Traceback (most recent call last):
       16: from org.jruby.RubyKernel$INVOKER$s$rbCatch.call(org/jruby/RubyKernel$INVOKER$s$rbCatch.gen)
       15: from org.jruby.RubyKernel.catch(org/jruby/RubyKernel.java:1237)
       14: from org.jruby.RubyKernel$INVOKER$s$0$0$loop.call(org/jruby/RubyKernel$INVOKER$s$0$0$loop.gen)
       13: from org.jruby.RubyKernel.loop(org/jruby/RubyKernel.java:1507)
       12: from org.jruby.RubyKernel$INVOKER$s$0$3$eval.call(org/jruby/RubyKernel$INVOKER$s$0$3$eval.gen)
       11: from org.jruby.RubyKernel.eval(org/jruby/RubyKernel.java:1091)
       10: from org.jruby.RubyKernel.evalCommon(org/jruby/RubyKernel.java:1129)
        9: from RUBY.evaluate((irb):27)
        8: from org.jruby.javasupport.JavaMethod.invokeStaticDirect(org/jruby/javasupport/JavaMethod.java:369)
        7: from org.jruby.javasupport.JavaMethod.invokeDirectWithExceptionHandling(org/jruby/javasupport/JavaMethod.java:457)
        6: from java.lang.reflect.Method.invoke(java/lang/reflect/Method.java:566)
        5: from jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(jdk/internal/reflect/DelegatingMethodAccessorImpl.java:43)
        4: from jdk.internal.reflect.NativeMethodAccessorImpl.invoke(jdk/internal/reflect/NativeMethodAccessorImpl.java:62)
        3: from jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        2: from java.sql.DriverManager.getConnection(java/sql/DriverManager.java:251)
        1: from java.sql.DriverManager.getConnection(java/sql/DriverManager.java:702)
Java::JavaSql::SQLException (No suitable driver found for jdbc:mysql://localhost/mydatabase?user=root)

问题似乎是 DriverManager 没有按照 JavaDocs 所说的去做。

调用 getConnection 方法时,DriverManager 将尝试从初始化加载的驱动程序和使用与当前小程序或应用程序相同的类加载器显式加载的驱动程序中找到合适的驱动程序。

有效的方法是显式创建驱动程序,并使用连接方法。

require 'jdbc/mysql'

Jdbc::MySQL.load_driver

url = "jdbc:mysql://localhost/mydatabase"
driver = Java::com.mysql.cj.jdbc.Driver.new
props = java.util.Properties.new
props.setProperty("user", "root")
props.setProperty("password", "")

conn = driver.connect(url,props)

我还创建了一个 java 程序来直接测试本质上相同的代码。它适用于 Java 11(相同的堆栈)。

import java.sql.DriverManager;

Connection conn = null;

conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase?" + "user=root");
java mysql jdbc jruby
© www.soinside.com 2019 - 2024. All rights reserved.