作为一个学校项目,我正在做一个多平台分布式数据库系统
我需要从 Java 数据库中提取数据,以便动态加载我的 jdbc 连接器
在 Windows 中完美运行
但是在 Linux 中我得到了错误:
“找不到适合 jdbc:mysql://... 的驱动程序”
这是代码:
File f = new File("mysql-connector-java-5.1.24-bin.jar");
URLClassLoader urlCl = new URLClassLoader(new URL[] { f.toURL()},System.class.getClassLoader());
Class conector = urlCl.loadClass("com.mysql.jdbc.Driver");
conector.newInstance();
Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/test","root","");
Statement instruccion = conexion.createStatement();
ResultSet tabla = instruccion.executeQuery("select * from prueba where uno=1");
while(tabla.next())
{
System.out.println(tabla.getString(1));
System.out.println(tabla.getString(2));
}
conexion.close();
我不知道我能做什么。
这样做是为了避免在每个站点上安装连接器
我传递一个包含每个数据库配置的文件,如果是 postgresql 加载 postgres jdbc conector 如果是 mysql 等...
建议?
最佳答案
为什么不直接将连接器放入 lib 子目录,然后将其中包含的所有 jar 传递给 Java 类路径?
示例文件夹树:
- 我的应用程序
- 斌
- 启动器.sh
- MyApp.jar
- 图书馆
- myLib.jar
- 斌
这是 launcher.sh 脚本:
#!/bin/sh
#Set basedir
LAUNCHER_DIR=$(cd $(dirname $0); pwd)
#Set Java Class-Path
CLASSPATH="$LAUNCHER_DIR/bin/MyApp.jar"$(find "$LAUNCHER_DIR" -name '*.jar' -printf ":%p")
#Launch application
java -cp "$CLASSPATH" com.company.MyApp $*
编辑:不建议直接使用 File.toURL如文档中所述,您必须执行 File.toURI().toURL()。
关于java - 在 Linux Java 中动态加载类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17084367/