jdbc dynamic class loading - java

hello i am trying to load my jdbc diver through classloader
here i am code but why i get this error if possible than give me some example
i don not what to set class path variable
i am making a database application and this application need to connect database again and again and i want to give this application to my friend but my friend not know about class path he is like normal user ,
my application can connect 4 type of database MS-Access,MySQL,Oracle,SQLlite...
in user system i have to set 5 class path variable and provide 5 jar file
if i give this application 100 people than they have set set class path variable
i can include jar file with my application but how can i set class path dynamically ....
please provide some example...
package classload;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ClassLoad {
static Connection con;
public static void main(String[] args) {
File jar = new File("C:\\query\\Driver.jar").getAbsoluteFile();
if(jar.exists()){
System.out.print("File exits");
}
URL urls[] = null;
try {
urls = new URL[] {
jar.toURI().toURL()
};
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClassLoader cl = new URLClassLoader(urls);
try {
Class.forName("com.mysql.jdbc.Driver", true, cl);
con=DriverManager.getConnection("jdbc:mysql://localhost", "root", "anil");
Statement stm=con.createStatement();
ResultSet result=stm.executeQuery("select *from actor");
while(result.next()){
System.out.print(result.getInt(1)+" "+result.getString(2)+" "+result.getString(3));
System.out.println("");
}
} catch (SQLException e) {
System.out.println(e);
}catch(ClassNotFoundException e){
System.out.println(e);
}
}
}
exception is
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost

Just use One-Jar to package the application and all of the dependencies into single fat jar. Your solution is no good. Your friend would have to use the same folder structure as you are in order for it to work.

This error is coming probably because the required jar file mysql-connector has not been included in your project. Try including jar file as shown here. And try this code to load Driver class:
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jlcstudents","root","password");

Related

NoClassDefFoundException while trying to use HikariCP [duplicate]

This question already has answers here:
Why am I getting a NoClassDefFoundError in Java?
(31 answers)
Closed 6 years ago.
I'm so noob at external stuff to Bukkit programming, so I'm sorry if it's so easy to solve :P
I have a problem, and it's that when I try to use HikariCP in my project, it returns in an error (the title one).
I'm using it in a BungeeCord plugin.
The weird thing is that I have done this successfully couples of times, and I don't know why it isn't working this time.
The error / log:
06:13:36 [ADVERTENCIA] Exception encountered when loading plugin: DiverseReport java.lang.NoClassDefFoundError: com/zaxxer/hikari/HikariDataSource at net.srlegsini.DiverseReport.Bungee.MClass.onEnable(MClass.java:44) at net.md_5.bungee.api.plugin.PluginManager.enablePlugins(PluginManager.java:227) at net.md_5.bungee.BungeeCord.start(BungeeCord.java:272) at net.md_5.bungee.BungeeCordLauncher.main(BungeeCordLauncher.java:55) at net.md_5.bungee.Bootstrap.main(Bootstrap.java:15) Caused by: java.lang.ClassNotFoundException: com.zaxxer.hikari.HikariDataSource at net.md_5.bungee.api.plugin.PluginClassloader.loadClass0(PluginClassloader.java:53) at net.md_5.bungee.api.plugin.PluginClassloader.loadClass(PluginClassloader.java:27) at java.lang.ClassLoader.loadClass(Unknown Source) ... 5 more
My main class:
package net.srlegsini.DiverseReport.Bungee;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import com.zaxxer.hikari.HikariDataSource;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import net.srlegsini.DiverseReport.Bukkit.UUIDFetcher;
public class MClass extends Plugin {
static Configuration config;
static MClass plugin;
static HikariDataSource hikari;
static Connection connection;
public void onEnable() {
BungeeCord.getInstance().getPluginManager().registerListener(this, new ChannelListener());
BungeeCord.getInstance().registerChannel("Return");
loadCfg();
if (!config.contains("MySQL")) {
config.set("MySQL.Enable", false);
config.set("MySQL.Host", "localhost");
config.set("MySQL.Port", 3306);
config.set("MySQL.User", "user");
config.set("MySQL.Pass", "pass");
config.set("MySQL.Database", "Sr_DiverseReport");
}
saveCfg(getDataFolder());
hikari = new HikariDataSource();
hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
hikari.addDataSourceProperty("serverName", config.getString("MySQL.Host"));
hikari.addDataSourceProperty("port", 3306);
hikari.addDataSourceProperty("databaseName", config.getString("MySQL.Database"));
hikari.addDataSourceProperty("user", config.getString("MySQL.User"));
hikari.addDataSourceProperty("password", config.getString("MySQL.Pass"));
try {
Class.forName("com.mysql.jdbc.Driver");
connection = hikari.getConnection();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e2) {
}
saveCfg(getDataFolder());
}
public void loadCfg() {
try {
File file = new File(getDataFolder(), "config.yml");
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
if (!file.exists()) {
file.createNewFile();
}
config = ConfigurationProvider.getProvider(YamlConfiguration.class)
.load(new File(getDataFolder(), "config.yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void saveCfg(File dataFolder) {
try {
ConfigurationProvider.getProvider(YamlConfiguration.class).save(config, new File(dataFolder, "config.yml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings({ "unused", "deprecation" })
public static String getUUID(String playerName) {
UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList("evilmidget38", "mbaxter"));
String playerUUID = null;
try {
playerUUID = UUIDFetcher.getUUIDOf(playerName).toString();
} catch (Exception e2) {
playerUUID = BungeeCord.getInstance().getPlayer(playerName).getUniqueId().toString();
}
return playerUUID;
}
}
My procedure:
Create the project, import BungeeCord.jar, HikariCP-2.6.0.jar and slf4j-api-1.7.21.jar in buildpath, import HikariCP-2.6.0.jar and slf4j-api-1.7.21.jar
It worked in other projects, but magically, it's broken.
I don't want to use Maven, just because it must have a fix, because as I said, I used this same procedure so many times in the past.
Thank you for taking the time to read this :)
EDIT:
Image of the project
It's all in the exception:
Caused by: java.lang.ClassNotFoundException: com.zaxxer.hikari.HikariDataSource
The HikariDataSource is missing at runtime, you need to provide it somehow, for example by copying the relevant .jar with 'drivers' into your server libraries folder.
Also see some related questions:
How to set up datasource with Spring for HikariCP? and
How do I configure HikariCP in my Spring Boot app in my application.properties files?
From the exception it is clear that HikariCP-2.6.0.jar was in classpath during compile time but is missing in runtime and from the image of the project structure, it is also clear that both HikariCP-2.6.0.jar and slf4j-api-1.7.21.jar are missing as library reference in the ide. You need to keep these jar in your classpath library during compile time and runtime.

How to make MongoDB Service Available?

I am developing OSGi Mongodb bundle I have also added the following dependencies
com.mongodb
org.apache.felix.fileinstal
org.amdatu.mongo
org.apache.felix.configadmin
and all the dependency managers but in gogo console I get the following error message
org.amdatu.mongo
org.osgi.service.cm.ManagedServiceFactory(service.pid=org.amdatu.mongo) registered
org.osgi.service.log.LogService service optional unavailable
[11] agenda.mongodb.mongo_gfs
agenda.mongo.inter.AgendaMongo() unregistered
org.amdatu.mongo.MongoDBService service required unavailable
the main problem is MongoDBService is not available I must require this service for solving this problem I have read the book according to them
From a development perspective, everything seems fine, but when you
run the appliā€ cation, it will complain that the MongoDBService is
unavailable. You can figure this out with the dmcommand in the shell.
We did however set up MongoDB on our system and deployed the necessary
dependencies in our runtime. Still, the MongoDBService was unable to
start. How come? This is because the MongoDBService needs some
mandatory configuration in order to know to what database to connect
to. The Amdatu MongoDB Serviceuses the Managed Service Factory pattern
(see Chapter 4), and in order to bootstrap it, we need to supply a
configuration file. In order to supply the configuration file, we need
to create a new folder in our agendaproject. Create a new folder
called load. This is the default name that the runtime will look for
in order to spot configuration files. Next, add an empty text file and
call it something like org.amdatu.mongo-demo.xml. The configuration
file needs at least the following information: dbName=demo
I have also apply this but its still unavailable.
This is interface:
package agenda.mongo.inter;
import java.io.InputStream;
public interface AgendaMongo {
public String store_in_db();
public InputStream getData(Object file_id);
}
This is the implementation for Mongodb:
package agenda.mongodb.gridfs;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import org.amdatu.mongo.MongoDBService;
import org.bson.types.ObjectId;
import agenda.mongo.inter.AgendaMongo;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
public class Gridfs_Mongodb implements AgendaMongo{
GridFSInputFile gfsinput=null;
private volatile MongoDBService mongoservice;
public String store_in_db() {
/*try {
GridFS gfsHandler;
gfsHandler = new GridFS(mongoservice.getDB(), "rest_data");// database
File uri = new File("f:\\get1.jpg"); // name and
gfsinput = gfsHandler.createFile(uri);
gfsinput.saveChunks(1000);
gfsinput.setFilename("new file");
gfsinput.save();
//System.out.println(gfsinput.getId());
//save_filepath("file",gfsinput.getId());
Object get_id = gfsinput.getId();//get_filename();
//System.out.println(getData(get_id));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
//System.out.println("Exception");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//System.out.println("Exception");
e.printStackTrace();
}*/
System.out.println("DB:" + mongoservice.getDB());
return mongoservice.getDB()+"";
}
/*
* Retrieving the file
*/
public InputStream getData(Object file_id) {
GridFS gfsPhoto = new GridFS(mongoservice.getDB(), "rest_data");
GridFSDBFile dataOutput = gfsPhoto.findOne((ObjectId) file_id);
DBCursor cursor = gfsPhoto.getFileList();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println(dataOutput);
return dataOutput.getInputStream();
}
void start(){
System.out.println("hello");
System.out.println(store_in_db());
}
}
Here I was just trying to get database name because every thing can be done after that but I t was returning me NULL because MongoDBService is Unavailable.
At this is Activator class
package agenda.mongodb.gridfs;
import org.amdatu.mongo.MongoDBService;
import org.apache.felix.dm.DependencyActivatorBase;
import org.apache.felix.dm.DependencyManager;
import org.osgi.framework.BundleContext;
import agenda.mongo.inter.AgendaMongo;
public class Activator extends DependencyActivatorBase {
#Override
public void init(BundleContext arg0, DependencyManager manager)
throws Exception {
manager.add(createComponent()
.setInterface(AgendaMongo.class.getName(), null)
.setImplementation(Gridfs_Mongodb.class)
.add(createServiceDependency()
.setService(MongoDBService.class)
.setRequired(true)));
}
#Override
public void destroy(BundleContext arg0, DependencyManager arg1)
throws Exception {
// TODO Auto-generated method stub
}
}
The Interface package is an exported package and the implementation package is private.
The configuration file should have a .cfg extension (not .xml).

In my application in java database connection code is not working

In this code class.forname it show error that class not found
so help me with this code because my is a local database application
I am using sqlite database.
package appview;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Databaseconnection {
Connection connection = null;
public static Connection connection2()
{
try
{
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Jainam\\Java Application\\JPH\\src\\database\\jph_db.sqlite");
return connection;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
You have to declare the url this way: jdbc:sqlite:/DRIVE:/dirA/dirB/dbfile
DriverManager.getConnection("jdbc:sqlite:/C:/Users/Jainam/Java Application/JPH/src/database/jph_db.sqlite");
See Here for more informations
ClassNotFoundException means Java is not able to find the org.sqlite.JDBC class. You need to Download sqlite-jdbc-3.6.20.1.jar and put it in your class-path before running it.
here check database connectivity.
class not found ? then go for DDMS->FILE EXP-> SDCARD -> INSERT UR SQLITE.DB file.It will run proper.

How to use Java Property File?

I need to use .properties file in Java to store database information.
Here is my database connector class. It's giving NullPointerException. What is the issue with my code ?
Note, that I haven't' assign those property file values. DB connection values are still hard coded.
import java.io.IOException;
import java.io.InputStream;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class Database {
public Connection connection;
private Statement statement;
private Properties property;
public static Database database;
private Database() {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "edus";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
InputStream is = Database.class.getClassLoader().getResourceAsStream(
"config.properties");
property.load(is);
System.out.println(property.getProperty("db_user"));
System.out.println(property.getProperty("db_password"));
System.out.println(property.getProperty("db_name"));
Class.forName(driver).newInstance();
this.connection = (Connection) DriverManager.getConnection(url + dbName,
userName, password);
}catch (IOException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
System.out.println("JDBC driver is missing");
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
public static synchronized Database getDatabaseConnection() {
if (database == null) {
database = new Database();
}
return database;
}
}
config.properties is not lying under classpath. It should be under classes folder.
you can also try
Database.class.getClassLoader().getResourceAsStream(
"com/lk/apiit/eduservice/config.properties");
As Roman C pointed out you also need to initialize Properties Object first
Properties property = new Properties();
You forgot to initialize
Properties property = new Properties();
This is an issue of NullPointerException in your code, because you referenced not initialized variable.
If you open a stream you should close it after it's not used. Do it by adding finally block.
The code where you getting a connection to the database you can move to the corresponding method. If the connection is closed you will not reinitialize the database again just reopen a connection or get a new one.
Dont keep config properties file in a package. Keep it directly inside the source folder, so that the config properties file comes directly in the build/classes folder after the build is done.
The issue is that your config properties in in the folder com/ik/apiit/eduservice folder but your code is expecting it to be directly in the classes folder (the root folder of classpath).
try this
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
prop.load(in);

Database Connection via WebLogic

So I have a MySQL database, and I have a datasource on a local instance of WebLogic which is connected to that database. I am trying to write some client code which will simply connect and query. I am having issues with obtaining a connection from the datasource. Here's my code thus far. I am running WebLogic 12c.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ConnectionTest {
public static void main(String... args) {
ConnectionTest tCon = new ConnectionTest();
tCon.TestConnection();
}
public void TestConnection() {
Context ctx = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("java.naming.factory.initial",
"weblogic.jndi.WLInitialContextFactory");
props.put("java.naming.provider.url", "t3://localhost:7001");
props.put("java.naming.security.principal", "weblogic");
props.put("java.naming.security.credentials", "welcome1");
ctx = new InitialContext(props);
DataSource ds = (DataSource) ctx.lookup("RegexDB");
System.out.println(ds);
DAO dao = new DAO();
conn = ds.getConnection();
stmt = conn.createStatement();
stmt.execute("select * from regular_ex");
rs = stmt.getResultSet();
ArrayList<HashMap<String, Object>> results = dao
.resultSetToArrayList(rs);
dao.printArrayList(results);
stmt.close();
conn.close();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
This fails at ds.getConnection() with the following exception:
java.lang.ClassCastException: weblogic.jdbc.common.internal.ConnectionEnv cannot be cast to java.io.Serializable
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2285)
at weblogic.utils.io.ObjectStreamClass.writeFields(ObjectStreamClass.java:414)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:235)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:225)
at weblogic.corba.utils.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:182)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1983)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:2021)
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2285)
at weblogic.jdbc.common.internal.RmiDataSource_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:695)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:520)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:516)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
I have wlclient.jar, wlsafclient.jar, and weblogic.jar in my buildpath. I have tried all sorts of combinations of adding/removing these jars, but I still get the same error regardless of what I do. Any help would be greatly appreciated.
After doing some research, I am deleting my old answer and starting over.
There is a large table of client types in the Oracle Doc for WebLogic Standalone Clients. For each type of client, listed, the table shows the required jar files. For certain types of clients, you need to build an additional jar (wlfullclient.jar) and include that.
Hope this helps.
I have also face this problem and I tried to add "wlfullclient.jar" to my directory to fix it out but I didn't find this jar file in weblogic installation folder.
But at the last I have set all required jar files form weblogic by using setDomainEnv.cmd and it works fine. Here we don't have to care about which jar files required or not it'll simply set classpath for all required jar file for your program.
I am using Weblogic 11g.
In Weblogic 12c, copy the weblogic.jar file to some other directory. Rename the file to weblogic-classes.jar and then build the jar file using wljarbuilder.
Add the newly created wlfullclient.jar file to your Class Path in eclipse.
Build wlfullclient.jar and add just this jar to the build path.
It solved the problem for me.
By the way weblogic.jar from Weblogic 12 is missing some classes as compared to weblogic.jar from Weblogic 10.3

Categories