I'm trying to make a program that connects to an Oracle database for the ultimate purpose of creating a few tables and running commands on them for a course I am taking. I'm currently trying to make the example given in class work but I can't get that to work. The code that generates the error "java.lang.ClassNotFoundException" is when my main hits the code:
Class.forName("oracle.jdbc.OracleDriver");
or
Class.forName("oracle.jdbc.driver.OracleDriver");
I have manually added the ojdbc6.jar, ojdbc8.jar and ojdbc14.jar files to each folder in my "PATH" system variable and I'm getting the exception:
java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver
or
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
I have no idea how to fix this or what to modify. It is a course example after all...
Any/All suggestions are welcome.
Thank you for your time
I hope this might help?
I don't think you need Class.forName with latest version.
I would have done something like below and set connection,url,user and password as global final variables to avoid repeating yourself and call the method where you need it.
public Connection getConnection() throws SQLException {
return connection = DriverManager.getConnection(url, user, password);
}
Related
This is the class where I connect sqlite
public static Connection ConnectDB() {
try {
Class.forName("org.sqlite.JDBC");
Connection con= DriverManager.getConnection("jdbc:sqlite:C:\\Users\\abh\\eclipse-workspace \\Training\\Database.db");
return con;
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,e);
return null;
}
}
The jar file inside the project folder name is sqlite-jdbc-3.7.2 I'm confused whether it's because of the version or if it's from my database created in sqlite
SQLite is a pretty good database platform, I highly doubt it's the problem as is the JDBC version your using as well.
The Connection method you presented does indeed work but you need to keep in mind that the connection has nothing to do with tables. It has everything to towards a connection to a particular SQLite database file and if the path doesn't exist to get to the database file specified, then it simply can not find that database. If the path does exist, and local system permissions allow it, and the database file does not exist, then the connection call will automatically create the database file specified but it will be empty. Never the less, the connection is now made and ready for a database Table to be either Created or Accessed via a query (providing there is actual data in the table).
If there was an error regards to the connection then you would receive a Message Box on the screen, and if you do then it's probably because of the whitespace that exists in the specified database path between eclipse-workspace and \\Training:
"jdbc:sqlite:C:\\Users\\abh\\eclipse-workspace \\Training\\Database.db"
Edit: Oh...as already specified by #lazylead :)
On a side: It's not a good idea to hard-code the path to your database file. This will never be the path when the application is run in the real world.
I am working on an EAR application(deployed on WLS 12c) that has a feature to configure and test jdbc connection for Oracle. So, in my jsp page the user selects the driver as oracle.jdbc.OracleDriver, enter the connectionurl, username and password and clicks on testConnection. And on doing this, the applicaiton gives back an error stating java.sql.SQLException: No suitable driver found for
jdbc:oracle:thin:#XXX-xx:1525/YYYY
A little brief of the architecture used in this application :
On application startup, we are referring to an xml that has all the JDBC defaults and try to load all the supported jdbc drivers that are present in that xml. And oracle.jdbc.OracleDriver is also one of them. This registering is done through a util class JDBCUtil.java which has 2 static methods : registerDriver(String driverName) and isDriverRegistered(String driverName).
So, the first time that JDBCUtil.registerDriver("oracle.jdbc.OracleDriver") is called, isDriverRegistered returns false and within registerDriver, we are making a call to class.forName(driverName) to load the driver.
The logic within isDriverRegistered gets an enumeration of all the drivers registered with DriverManager by calling DriverManager.getDrivers and checks if the driverName string passed to it equals driver.getClass.getName.
After the 1st call to JDBCUtil for OracleDriver, any subsequent calls to registerDriver for OracleDriver is expected to skip the class.forName because the isDriverRegistered is expected to return true. But upon adding logs statement and debugging, i noticed that everytime registerDriver->isDriverRegistered is called for OracleDriver, it is always returning false. The enumearation obtained by calling DriverManager getDrivers, never contains OracleDriver.
Secondly, In another class JDBCDS.java, we are calling JDBCUtil.registerDriver("oracle.jdbc.OracleDriver") and as expected, in registerDriver function exceute Class.forName("oracle.jdbc.OracleDriver") because isDriverRegistered returns false . In JDBCDS.java, after the call to registerDriver, we call DriverManager.getConnection by passing in the url,usename and password. And this call is throwing SQLException saying NoSuitableDriverFound.
So, as another debug test, i called Class.forName("oracle.jdbc.OracleDriver") in JDBCDS.java and then made a call to DriverManager.getConnection and this time i was able to get a connection successfully.
I have gone through all the question related to NoSuitableDriverFound exception on this forum, but nothing is fitting my issue.
I have tried to call create a new instanc of the driver by calling new oracle.jdbc.OracleDriver() within JDBCDS.java and see if it accepts my url and it does. Moreover, this has also ruled out any classpath problem. The jar is certainly in the classpath. Our classpath includes the following:
com.oracle.db.jdbc7-dms.jar and also weblogic.jar
com.oracle.db.jdbc7-dms.jar internally has a link to ojdbc8dms.jar and weblogic.jar internally has ojdbc8.jar included through the Class-Path attribute of its MANIFEST.MF files in both the cases.
Also, this issue is isolated to only a particular environment. In other environments with the same setup, everything works fine without issues.
From JDBCUtil.java :
static Util Method that is used to register the driver :
public static void registerDriver(String driverName)
{
// Calls isDriverRegistered,isDriverRegistered returns false, then call Class.forName(driverName)
}
static method to see if driver is alreay registered :
public static boolean isDriverRegistered(String driverName)
{
//call DriverManager.getDrivers to get all the registered drivers
if(driver.getClass().getName().equals(driverName))
{
return true;
}
return false;
}
Code in JDBCDS.java that is used to perform the test connection:
try {
JDBCUtil.registerDriver(driver);
DriverManager.setLoginTimeout(300);
conn = DriverManager.getConnection(url, username, password); //This code throws No Suitable Driver Found Exception
} catch (SQLException e) {
// tried the below as a test
try
{
Class.forName(driver);
}
catch(Exception ex)
{
Logger.log("Could not load the driver with the current classloader", 4);
throw e;
}
conn = DriverManager.getConnection(url, username, password);//At this step the connection is successfully obtained
}
Both JDBCUtil.java and JDBCDS.java are in the same package.
Can anybody point me towards what i can do further to resolve this issue?
I am browsing this website for quite some time now. The community helped me quite a lot, even though I never registered. Thanks for that.
However, this time I can't find a solution to my problem just by browsing, so I decided to register here and state my question so that someone might be able to help me.
First of all I'd like to say, that I'm basically at the beginning of my studies, so I'm not very knowledgeable yet. At the moment I'm learning for a upcoming exam and I need to know about databases. The Database of choice is Postgresq. But to really understand something like that, you need to try it out and not just read about it.
I'm not exactly sure what information are exactly required. But I'm using Windows 7, pgadmin and eclipse for that, all of them should be up to date. If you need further information, please ask for it.
I used a Tutorial to get it up and running, however I'm not able to establish a connection to the database using eclipse. The DriverManager.getConnection() causes a UTF-8 error I'm not understanding nor able to fix it.
org.postgresql.util.PSQLException: The connection attempt failed.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:280)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:67)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:212)
at org.postgresql.Driver.makeConnection(Driver.java:407)
at org.postgresql.Driver.connect(Driver.java:275)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.hywy.TestConnection.main(TestConnection.java:23)
Caused by: java.io.IOException: Illegal UTF-8 sequence: initial byte is 11111xxx: 252
at org.postgresql.core.UTF8Encoding.decode(UTF8Encoding.java:131)
at org.postgresql.core.PGStream.ReceiveString(PGStream.java:331)
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:447)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:223)
... 7 more
The Code I'm using is:
import java.sql.*;
import java.util.Properties;
//import com.hywy.db.DbContract;
public class TestConnection {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("user", "postgre");
properties.setProperty("password", "random_password");
//properties.setProperty("ssl", "true");
String url = "jdbc:postgresql://localhost:1112/people";
try {
Class.forName("org.postgresql.Driver");
// Connection c = DriverManager.getConnection(
// DbContract.HOST+DbContract.DB_NAME,
// DbContract.USERNAME,
// DbContract.PASSWORD);
Connection con = DriverManager.getConnection(url, properties);
//Connection c = DriverManager.getConnection("jdbc:postgresql://localhost:1112/people" , "postgre" , "random_password");
System.out.println("DB connected");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
The code is a bit of a mess, since I Googled some time for it and tried some stuff. I was not sure if I should paste the out-commented code with the rest of it, but at least you can see that I already tried some things.
I also tried a different port, at first I was using the standard port (5432) but it made no difference.
I also linked the up-to-date jdbc jar file in my build path.
I hope someone knows (about) this problem and is willing to help me.
Thanks in advance.
Excuse my English, it's not my native tongue.
Ok guys, I just wanted to say that I fixed the problem. I also wanted to thanks anyone who tried to help me.
It's only logical that no one was really able to help me, because it was only due to my stupidity.
The mistake happened at
"jdbc:postgresql://localhost:1112/people"
Only when I did the whole thing on another computer, to see if it's my system, I realized I'm not supposed to write the actual table name at the end of the line, but instead the name of the Database, so I just changed "people" into "postgres" and it worked.
Sorry for the stupid question, I hope my next one will be better :)
*Topic can be deleted or closed or whatever you want to do with it.
Thanks anyone!
I am wondering how JDBC knows which database driver class it should use.
Example:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection verbindung = DriverManager.getConnection("jdbc:derby:d:/memory/onlineshop;create=true");
The first line takes Care, that a driver (EmbeddedDriver) will be loaded into to class loader (and so be available, e.g. for using with reflections, right?).
So, the next line is my connection string. It starts with:
jdbc:derby:...
I expected something like this instead:
jdbc:ConcreteDriverClassForInit
As you can see i am missing a link between the class loaded in the class loader and the connection string call of that class.
I searched in the derby archive for a class named "Derby.Class" - but there is no such class.
Even when I try sth. like this, JDBC still knows, what to do:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Class.forName("org.something.anyotherDBDriver1");
Class.forName("org.something.anyotherDBDriver2");
Connection verbindung = DriverManager.getConnection("jdbc:derby:d:/memory/onlineshop;create=true");
But why?
Thanks for your help!
That EmbeddedDriver class has a static block executed when you load the class that adds an handler for the specific JDBC type:
static {
EmbeddedDriver.boot();
}
Check the code of the boot method here, and you'll see where the protocol is registered:
new JDBCBoot().boot(Attribute.PROTOCOL, ps);
That specific string is located in org.apache.derby.iapi.reference:
String PROTOCOL = "jdbc:derby:";
That's a common pattern that is followed by all JDBC drivers, i don't particularly like the code of this driver, if you want a cleaner example look at the SQLite driver, way more straightforward implementation:
static {
try {
DriverManager.registerDriver(new JDBC());
}
catch (SQLException e) {
e.printStackTrace();
}
}
org.sqlite.JDBC will register itself to the java.sql.DriverManager that will invoke JDBC.isValidURL(String url) to know if this class is a valid driver for a specific JDBC url, the SQLite driver will return true only if the url contains the PREFIX jdbc:sqlite:.
In previous versions of JDBC, to obtain a connection, you first need to load your JDBC driver by calling the method Class.forName().
Currently any JDBC 4.0 drivers that are found in your class path are automatically loaded. So, there is not even the need for Class.forName().
The gist of it is to be found in the documentation for java.sql.Driver and java.sql.DriverManager.
Basically, starting with JDBC 4, all you have to do is create a META-INF/services/java.sql.Driver file for your SQL driver implementation and the JRE will load it automatically. Which means that you can directly try and do:
DriverManager.getConnection("yourUrlHere")
If one driver recognizes the URL, it will be used automatically.
I am attempting to combine two disparate data sources into one MBO. The sybase documentation states that you have to develop a custom result set filter in java. Ok. No big deal. I am somewhat familiar with JDBC Rowsets so I think I can probably handle this. So I go grab JConnect 7 and am attempting to use the JDBC driver in my result set filter to get a result set that I can use to filter the data set returned from the web service I am connecting to. I have tested my connection with the simple test below:
try
{
DriverManager.registerDriver((Driver)Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance());
Connection conn = DriverManager.getConnection("jdbc:sybase:Tds:localhost:5500", "dba", "sql");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select * from traveler where traveler_id = 1");
while (rs.next())
{
System.out.println(rs.getRow());
}
} catch (Exception se)
{
se.printStackTrace();
}
Of which I get a rowcount of one back, which is what I am expecting. The problem is when I implement this same code in the ResultSet filter class, and attempt to preview it in the MBO, I get the following error in the eclipse debug console (distilled for clarity):
22:14:20 [ERROR] [ExecuteSection]: Execution error
java.lang.reflect.InvocationTargetException...
[...]
Caused by: java.lang.UnsatisfiedLinkError: no dbjodbc11 in java.library.path
This looks like a classpath issue, but I have the Jconnect jar in my build path, and that is verified by the fact that my little test runs successfully. Is this an eclipse issue.. is eclipse using a different classpath when executing code for the Mobile workspace project?
Can't remember the exact path right now, but there is a third-party lib folder under the <SybaseInstallation>/UnwiredWorkspace folder. Try adding your jar there.