[英]Dynamically load class in Linux Java
I'm doing as a school project a multi-platform Distributed Data Base System 我正在做一个学校项目的多平台分布式数据库系统
I need to extract data from the Data Base in Java so i dynamically load my jdbc connector 我需要从Java的数据库中提取数据,所以我会动态加载我的jdbc连接器
Works Perfect in Windows 在Windows中完美运行
But in Linux I got the error: 但是在Linux中,我得到了错误:
"No suitable driver found for jdbc:mysql://..." “找不到适合的驱动程序jdbc:mysql:// ...”
This is the code: 这是代码:
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();
I don't know what can I do. 我不知道该怎么办。
This it's made to avoid the installation of the connector on each site 这样做是为了避免在每个站点上都安装连接器
I pass a file with the configuration for each DB, if is postgresql load postgres jdbc conector if is mysql etc... 我通过每个数据库的配置传递文件,如果是PostgreSQL加载postgres jdbc conector如果是mysql等...
Suggestions? 有什么建议吗?
Why don't just put the connector into a lib sub-directory and then passed all jar contained in this one to the Java Class-Path ? 为什么不只是将连接器放在lib子目录中,然后将其中包含的所有jar传递给Java Class-Path?
Samples folder tree : 样本文件夹树:
Here is the launcher.sh script : 这是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 $*
EDIT: It is not recommanded to directly use File.toURL as describe in the documentation, you must do File.toURI().toURL(). 编辑:不建议直接使用File.toURL ,如文档中所述,您必须执行File.toURI()。toURL()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.