JDBC driver - ClassNotFoundException, NetBeans - java

I've searched a lot and spent many time trying register JDBC driver.
First, I copied my ojdbc7.jar file (downloaded from Oracle) into directory shown below:
Driver File(s): /Users/Kamil/glassfish4/jdk7/jre/lib/ext/ojdbc7.jar
Driver Class: oracle.jdbc.OracleDriver
// this is copied from Services/Databases/Drivers/ojdbc
Then, I tried following code:
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(myDriver);
} catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
... and this one:
try {
Class.forName("oracle.jdbc.OracleDriver");
} catch (ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
... and with this line instead:
Class.forName("oracle.jdbc.driver.OracleDriver");
I always get ClassNotFoundException :(
Here is code I try to run:
Connection DBconn;
String USER = "root";
String PASS = "root";
System.out.println("Connecting to database...");
DBconn = DriverManager.getConnection("mysql://localhost:3306/RestToolDatabase", USER, PASS);
System.out.println("Creating statement...");
Statement stmt = DBconn.createStatement();
String sql;
sql = "select surname, id, age\n"
+ "from customers \n"
+ "where name = \"maria\" \n"
+ "order by id;";
ResultSet rs = stmt.executeQuery(sql);
I've also read about setting the classpath as described here:
Right-click your Project.
Select Properties.
On the left-hand side click Libraries.
Under Compile tab - click Add Jar/Folder button.
but there is no "Properties/Libraries" option in NetBeans...
I use Maven and there is following dependency added by some library:
<dependency>
<groupId>ojdbc</groupId>
<artifactId>ojdbc</artifactId>
<version>14</version>
<type>pom</type>
</dependency>
Maybe there is some workaround, or other way to add it automatically? It SHOULD be simple but I'm unexperienced and wasted many time on this. Please help.
EDIT: Thank you for replies, yes, I use MySQL Server at localhost:3306 [root]. I have MySQL JDBC connector installed here:
/Applications/NetBeans/NetBeans 8.0.app/Contents/Resources/NetBeans/ide/modules/ext/mysql-connector-java-5.1.23-bin.jar
When I go to "Services" --> "Drivers" --> "MySQL (Connector/J driver)" there is Driver Class path exactly as you suggested, so I use Class.forName("com.mysql.jdbc.Driver") now.
I right-clicked on "MySQL (Connector/J driver)" driver and went to "Connect Using..." --> "localhost, port 3306, user, password". And it is connected now, I see new connection. But still I get ClassNotFoundException.
EDIT 2 - this solution worked for me:
I added following to dependencies in pom.xml:
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.23</version>
</dependency>
... and builded application; the driver was downloaded and installed. As simple as that... I spent many time on this... It works - yeah! :)

You are using an Oracle JDBC driver on a MySQL database, you should use
Class.forName("com.mysql.jdbc.Driver");
Edit: Thanks to the comments from #duffymo and #Mark-Rotteveel who noticed that the URL of the connection is also wrong, the correct connection is:
Connection DBconn;
String USER = "root";
String PASS = "root";
DBconn = DriverManager.getConnection("jdbc:mysql://localhost:3306/RestToolDatabase?" + "user="+USER+"&password="+PASS);

Setting the classpath :
Download the JAR JDBC Connector/Driver
Copy file in subfolder of project (ex: libs) (not 'src')
Project->Properties->Libraries->Add Jar/Folder->Select file
And packaging dependent librairies with relative path in 'dist' :
Project->Build->Packaging->Check "Copy Dependent Librairies"

I don't think the JDBC JAR belongs in that directory. The CNF exception backs me up.
I would recommend putting that JAR in your project WEB-INF/lib, repackaging the WAR, and trying again.
This line is correct:
Class.forName("oracle.jdbc.driver.OracleDriver");
The full class name has to match that in the JAR. This is the only one that does.
You have to use the driver that matches your database: Oracle for Oracle, MySQL for MySQL. What database are you using?

</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.23</version>
This worked for me. Since there's no Property and Library in Netbeans apache. Good luck.

Related

No Suitable Driver error after setting CLASSPATH, Maven, and pom.xml

Since yesterday I have been trying to figure out how to fix this SQLException, and at this point I'm empty. I have checked dozens of sites, the whole documentation for Microsoft and Azure on how to connect with databases, and I keep getting the same error.
I've added a CLASSPATH like CLASSPATH =.;C:\Program Files\Microsoft JDBC Driver 8.2 for SQL Server\sqljdbc_8.2\enu\mssql-jdbc-8.2.2.jre11.jar as informed on Using the JDBC Driver documentation. I've downloaded the JDBC driver from Microsoft themselves and dumped the files on a folder in C:\Program Files\Microsoft JDBC DRIVER 8.4 for SQL Server as their documentation suggests. My maven and java are working fine, and I have an example class that I've got from SQLExamples by Microsoft themselves, this one:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// As informed on:
// https://www.microsoft.com/en-us/sql-server/developer-get-started/java/windows/step/2.html
public class App {
public static void main(String[] args) {
String connectionUrl = "jdbc:sqlserver:[AzureAddressHere];"
+ "database=[DatabaseHere];"
+ "user=[UserHere];"
+ "password=[PasswordHere]";
try {
// Load SQL Server JDBC driver and establish connection.
System.out.print("Connecting to SQL Server ... ");
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
System.out.println("Done.");
}
} catch (SQLException e) {
System.out.println();
e.printStackTrace();
}
}
}
I've also added the references to the jar file to the pom.xml dependencies list:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.4.1.jre11</version>
</dependency>
I've also found a mention in a website that the jar file sits in Maven's library folder, so I've copied the jar file to the lib folder as well.
Yet, whenever I try to run the app, I get the java.sql.SQLException: No suitable driver found for [AzureInformation].
Any ideas on what I could be missing here?
Turns out that the issue was the lack of two // in the address. facepalm
So, I just set this line to: String connectionUrl = "jdbc:sqlserver://[AzureAddressHere];" and it finally connected.
To be fair to myself here, this error is so completely unclear and unhelpful.

ClassNotFoundException when using JDBC [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 2 years ago.
When I run my code, I get this error: Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver; with a stack trace link to line 13 (Highlighted in the code)
I have just started using JDBC and don't know much about it, but I'll go through what I have done so far to get to where I am. As a preliminary, I am using MySQL Workbench and Apache Netbeans 11:
1) Downloaded the .jar connector file
2) Could not find the build path on netbeans 11 and did some research and couldn't find any resources linking to it, so instead used the Driver dropdown through the databases section on the services tab. Now I can see all my SQL databases and tables in my netbeans IDE.
3) Wrote the following code using the 7 steps to connect to the database, establish a connection etc
import java.sql.*;
public class GroundControlToMajorTom {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306//customers";
String uname = "root";
String pass = "";
String query = "SELECT customer_id FROM customers WHERE customer_id = 1";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname, pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String id = rs.getString("customer_id");
System.out.println(id);
st.close();
con.close();
}
}
4) Run the code and get a ClassNotFoundException. I did a bit of research and it seems to say that I don't have the connection to the actual driver, but I added it in the drivers section of the services for my project?
Any help would be much appreciated my dudes <3
Add com.mysql.jdbc.Driver to CLASSPATH.
If you use maven, add to <dependencies> section of pom.xml the dependency of required driver (mysql-connector-java):
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
for gradle
compile group: 'mysql', name: 'mysql-connector-java', version: mysqlVersion
You need to add the downloaded JAR to the classpath.
Try this instruction:
Open NetBeans and right-click on the project name in the Projects tab.
Select Properties.
Select Libraries.
Click the Add Jar/Folder button.
Navigate to the directory where the downloaded JAR files are.

Maven: No suitable driver found for jdbc::mysql://google

I'm trying to connect my Java Maven project (which runs on a Jetty server) to a Google Cloud MySQL Database with the following code:
private static final String CREDENTIALS_STRING = "jdbc::mysql://google/weatherplanning?cloudSqlInstance=csci310-project-2:us-central1:myinstance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false&user=xxxx&password=xxxx";
try {
System.out.println("Connecting to database...");
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(CREDENTIALS_STRING);
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I've included both of these dependencies in my pom.xml:
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory-connector-j-8</artifactId>
<version>1.0.15</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
I'm getting
java.sql.SQLException: No suitable driver found for jdbc::mysql://google...
and I don't know what to do. I assume the dependencies should handle adding the JDBC driver to my classpath.
Your problem looks like you have a typo in your JDBC url. Your URL should start with jdbc:mysql instead of jdbc::mysql.
Additionally, you should always use a connection pool (like Hikari). Connection pools have many benefits, including better error handling, exponential backoff, and reduced latency.
You can view Hikari being used with the Cloud SQL JDBC socket factory in the context of a web application in this sample. Full instructions for deploying it are in the sample's README.

Installing MS SQL driver into Eclipse Maven [duplicate]

This question already has answers here:
Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0
(11 answers)
Closed 6 years ago.
How do I install MSSQL driver in my project with Eclipse's maven? (m2e)? And also make it not conflict with Vaadin? When I install the MSSQL driver locally following these instructions, during the compile and runtime, it says "Could not find archetype from Vaadin-addons."
I have the code:
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://server;databaseName=dbname;user=username;password=password");
String sql = "Select * from Table1";
stmt = con.createStatement( );
rs = stmt.executeQuery(sql);
while (rs.next()){
contractorsList.addBean(new Contractor(rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5),
rs.getString(6)));
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}finally{
try { con.close(); } catch (SQLException e) {}
try { rs.close(); } catch (SQLException e) {}
try { stmt.close(); } catch (SQLException e) {}
I'm getting the following error:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:450)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:403)
at java.lang.Class.forName0(Native Method)
Which means that it can't find my driver, I think. So I'm following this tutorial on installing the MS SQL driver. I download the driver from microsoft and then I unzip it here:
C:\SQLDriver
In Eclipse, on my project folder, I right click > Debug As > Debug Configurations >
mvn install:install-file -Dfile=C:\SQLDriver\sqljdbc_4.0\enu\sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0.2206.100 -Dpackaging=jar
Then I add in the following in my POM
<properties>
<!–….other versions–>
<sqlserver.version>4.0.2206.100</sqlserver.version>
</properties>
...
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>${sqlserver.version}</version>
</dependency>
I get an error that it can't find my dependency, So I look up the question here, and I found out that I simply need to add sqljdbc4 to my classpath.
I have no idea what that means but google took me here So I attempt to follow the instructions.
In System Properties > Advanced > Environment Variable under Variables, I add the following:
I searched here and it looks like someone else asked the same question
I honestly don't know what people mean by add it to the classpath. Do they mean paste the jars in the same folder as the project? Either way, I just found a .classpath file in my project and added these:
How do I get maven to use this microsoft sql driver?
[Edit] When going to Libraries > Maven Dependencies, right click > build path > configure build path, I see this:
Which, when I click, it doesn't let me edit the path of that file. I'm not sure where to edit it.
You will need to download the source code and the java docs for all the maven dependencies. You can do that by right clicking the maven as discussed here:
https://stackoverflow.com/a/22352526/1475228
Then only you can run the code.
Also look here. This is the one that helped mine.

java.sql.SQLException: No suitable driver found for jdbc:sqlserver [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 3 years ago.
I am working on a web application where I am creating MSSQLSERVER 2008
database dynamically.
But it's giving me
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost:1433;databaseName=master
My code is:
String dbName = "db1";
try {
String url = "jdbc:sqlserver://localhost:1433;databaseName=master";
Connection connection = DriverManager.getConnection(
url,
"sa",
"roshan14121987");
Statement statement = connection.createStatement();
String sqlquery = "CREATE Database \"" + dbName + "\"; ";
statement.executeUpdate(sqlquery);
statement.close();
connection.close();
} catch(Exception e) {
e.printStackTrace();
}
I have added sqljdbc4.jar in lib. I have tried it on both NetBeans (with GlassFish and Tomcat Server) and Eclipse IDE(Tomcat Server).
On the other hand I have tried this with simple desktop application, it's working fine on both IDEs. With sqljdbc4.jar added in lib.
Before calling DriverManager.getConnection() you will have to load the SQLServer JDBC driver. You can do Class.forName("xxxx"); where xxxx is the appropriate driver class (fully qualified name with package prefix).
EDIT: Do this Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); to load the driver. Refer MSDN link for more.
Is sqljdbc4.jar in your war file under WEB-INF/lib. This is the alternate location to $CATALINA_HOME/lib and recommended to keep your web application self-contained. Further, if you should ever need to change servers, you need only drop the war into your webapps directory.
You might also need a Class.forName([database class]).newInstance, but that isn't necessary using a JDBC 4.0 driver. Good luck and if you have further problems, do leave a comment.
The error happen in the runtime on Tomcat Server,right? I think you need to make sure your sqljdbc4.jar deploy the in the Server.

Categories