Error: java.lang.ClassNotFoundException: com.mysql.jdbc.Drivercom.mysql.jdbc.Driver - java

Im trying to establish a connection but having the mentioned error.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/cams?zeroDateTimeBehavior=convertToNull", "root", "root");
System.out.println("Connected to Database successfully");
Statement st = conn.createStatement();
s.assignStall(s.numOfStall + 1, stallOwnerId, category, iCanSelected,
contact, name, add, email, unitNo, stallName);
s.showAssignedStall();
/*
int result = st.executeUpdate(
"INSERT INTO StallOwner" (sId, sCat, cant, sContact,
sName, sAdd, sEmail, sUnitNo, sStallName) VALUES(
"")
)
*/
jTextFieldUserId.setText("");
jTextFieldName.setText("");
jTextFieldAddress.setText("");
jTextFieldContact.setText("");
jTextFieldEmail.setText("");
jTextFieldUnitNo.setText("");
jTextFieldStallName.setText("");
} catch (Exception e) {
System.out.println("Error: " + e.toString() + e.getMessage());
}
}
This is my 1st time with JDBC. Please help

Your will need to add the jar file containing the mysql driver to the classpath.

you have forgotten to include the mysql.jar
if you are using ECLIPSE IDE then follow these steps
right click on your project
go to buildpath
click configure build path
click add external jars
give the path to mysql.jar

You are missing mysql jdbc jar(jar containing the class com.mysql.jdbc.Driver) on your classpath. Add the required jar on your classpath.

Related

Getting ClassNotFoundException while working on derby databse from Glassfish on Netbeans [duplicate]

This question already has answers here:
How do I resolve ClassNotFoundException?
(28 answers)
Closed 2 years ago.
This is the code I've written:
package JDBC;
import java.sql.*;
public class JDBC {
public static void main(String[] args) {
try{
String driverName = "org.apache.derby.jdbc.ClientDriver";
String dbURL = "jdbc:derby://localhost:1527/Student";
String dbUser = "DV";
String dbPass = "Pass";
Class.forName(driverName);
Connection con = DriverManager.getConnection(dbURL, dbUser, dbPass);
Statement stmt = con.createStatement();
String sql;
sql = "create table Student(Enroll_No Varchar(20), Name Varchar(20), Gender Char, Age Int, CGPA Float, Email_ID Varchar(30))";
stmt.executeUpdate(sql);
stmt.close();
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
The error I'm getting is:
run:
java.lang.ClassNotFoundException: org.apache.derby.jdbc.ClientDriver
BUILD SUCCESSFUL (total time: 0 seconds)
and no table is created. I'm using Glassfish 4.1.1(Derby Database) on NetBeans IDE 8.2
For a ClassNotFoundException, you might want to check about missing .jar files in your project library.
Go to your Project Folder on Netbeans (top left corner), then Libraries and then check for "derbyclient.jar" and "derby.jar" files.
If they are not present, add them manually from your GlassFish folder.
Right click on Libraries -> Add JAR/Folder... Browse to your Glassfish 4.1.1 installation folder -> javadb -> lib and select derbyclient.jar and derby.jar files.
This should work and the exception shall be removed.

java.lang.ClassNotFoundException: com.sql.jdbc.Driver

I have been starting off with some JDBC a few days ago as of 2019/3. And there was this error occurring when I try to comply the code below in my eclipse IDE.
I actually did some research before this and I have tried:-
-Adding external libraries from the project menu
-Reinstalling and trying out different ides(thinking it was just eclipse but turns out its something about my system)
-reinstalled both jdk and the jdbc connector
and still, the problem persists.
import java.sql.*;
public class Driver{
public static void main(String[]args)throws Exception {
String url = "jdbc:mysql://localhost:3306/main";
String uName = "Ng Jun Han";
String pW = "password";
String query = "SELECT first FROM students WHERE id = 1";
Class.forName("com.sql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uName, pW);
Statement st = con.createStatement();
ResultSet rs= st.executeQuery(query);
rs.next();
String name = rs.getString("first");
System.out.print(name);
st.close();
con.close();
}
}
This is how my project directory looks like
My biggest concern regarding the topic is about something wrong I did with the installation methods. Mainly because there are not much up-to-date resources to follow.If so, does anyone know the CORRECT way of fixing it?(the driver jar file is located at C:\Program Files\MySQL , and i c/p-ed it into my the libraries file in my project directory) Thanks for helping:)
Try this class name :
Class.forName("com.mysql.cj.jdbc.Driver")
Refer to the official docs

"Could not create connection to database server" netbeans google cloud sql error

I am trying to create my first API using java httpServlet and netbeans which will be connected to a database on google cloud based its examples and documentations. I have not created the database, but I was given the necessary credentials and vars to create the connection. So I have downloaded the project from github, and when I tried to open it from netbeans there was some issues concerning dependencies ... So I resolved them, I replaced the credentials with their values and run the project; Unfortunately an error was thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. I made some searches but did not get any result... Could it be an error from this code ? an error from database security if it was invisible on cloud? Any help is more than appreciated.
public class ListTables {
public static void main(String[] args) throws IOException, SQLException {
String instanceConnectionName = "<foo:foo:bar>";
String databaseName = "myDatabaseName ";
String username = "myUsername ";
String password = "<myPass>";
if (instanceConnectionName.equals("<insert_connection_name>")) {
System.err.println("Please update the sample to specify the instance connection name.");
System.exit(1);
}
if (password.equals("<insert_password>")) {
System.err.println("Please update the sample to specify the mysql password.");
System.exit(1);
}
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
databaseName,
instanceConnectionName);
try{
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
/* try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("select * from wf_accounts;");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}*/
}catch(Exception ex){
System.out.println("Error: " + ex.toString());
}
Update
Same error was thrown when I did this:
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
"",
"");
Any hints?
First you have to check whether the mysql server is running on.If you are Windows user you can simply
Go to Task Manager
Go to Services
then search for your Mysql server(eg:for my case its MYSQL56)
then you will see under the status column it says its not running
by right clicking and select start
If it's already running then you have to do as in mysql Documentation,
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem

My puzzle about JDBC4.0 new feature: No suitable driver found

Guys,
I know there are some new features in JDBC4.0 and one of them is that you don't need to load database drivers explicitly as the JDBC API will automatically load the driver when you call getConnection(). So I just wanna test it.
BTW, I use Eclipse as my Dev Tool.
Here are my code snippets:
public class Test002JDBCRowSet {
public static void main(String[] args) throws Exception{
String connURL = "jdbc:oracle:thin:#192.168.1.150:1521:";
String database = "bmdw";
String userName = "bmdw";
String passWd = "bmdw";
String driver = "oracle.jdbc.driver.OracleDriver";
String SQLStr = "select t.Empno, t.Ename, t.job, t.sal from employer t where t.sal > 1500";
/*
try{
Class.forName(driver);
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
}
*/
//Latest Method4 : Search for some data with RowSet, offline!
RowSetFactory rsf = RowSetProvider.newFactory();
try(
Connection conn = DriverManager.getConnection(connURL + database,userName,passWd);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQLStr);
CachedRowSet cachedRS = rsf.createCachedRowSet();){
cachedRS.populate(rs);
conn.close();
System.out.println("======Employee List -- Salary more than 1500======");
System.out.printf("%-15s%-15s%-15s%-15s%n","Employee No.","Employee Name","Employee Job","Employee Salary");
try{
while(rs.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
while(cachedRS.next()){
System.out.printf("%-15d%-15s%-15s%.2f%n",cachedRS.getInt(1),cachedRS.getString("ENAME"),cachedRS.getString("JOB"),cachedRS.getFloat(4));
}
}catch(SQLException sqle){
sqle.printStackTrace();
}
}
}
I got the runtime exception :
java.sql.SQLException: No suitable driver found for
jdbc:oracle:thin:#192.168.1.150:1521:bmdw
However, if I remove the comments about loading oracle driver explicitly, it works well.
And I'm sure I have already add the ojdbc14.jar into classpath.
So I don't know what happened. I'm trying to figure out how does the method 'getConnection()' works.
I checked System.getProperties() but there is no property named 'jdbc.driver'. Even if I added it and set the value to 'oracle.jdbc.driver.OracleDriver'. It still doesn't work.
I checked ClassLoader.getSystemResources("META-INF/services/" + Driver.class.getName()) and I found there is only one default file :
jar:file:/D:/Java/jdk1.7.0_03/jre/lib/resources.jar!/META-INF/services/java.sql.Driver
I has so far achieved little.
There might be some oversight in the configuration of Eclipse.
Hope anyone can help me.
Thanks.
I agree with #kordirko and his comment. OP also seems to have confirmed that his problem is resolved because of his comment. Hopefully he gets notification of this and makes it an answer. :)
Check this link: http://docs.oracle.com/cd/E11882_01/java.112/e16548/jdbcvers.htm#JJDBC28109 --> You need to have the ojdbc6.jar in your classpath environment variable in order to have JDBC 4.0 standard support. – kordirko

Why am I receiving this SQLException error stating that no suitable driver can be found?

I'm on a mac, running a MAMP instance of MySQL. I'm trying to use a jdbc driver to connect my java code to a database called 'test', working with a table called 'customer.' I keep getting an error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8889/test
I'm not sure if the problem is with my code, or if it's a configuration problem with the MAMP instance of MySQL, or if it's something else entirely.
I have an initialize driver method:
public void initializeDriver(){
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println(e.toString());
}
}
And I have a connection created in the following way:
public void insertCustomer(String connectionUrl, String connectionUser, String connectionPassword, Customer customer) {
try{
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
Statement constat = conn.createStatement();
String query = "INSERT INTO customers (customer_id, email, deliverable, create_date) VALUES (" + customer.id + ", " + customer.emailAddress + ", " + customer.deliverable + ", " + customer.createDate + ")" ;
constat.executeQuery(query);
conn.close();
}
catch(SQLException e){
System.out.println(e.toString());
}
}
And I have downloaded mysql-connector-java-5.1.20 and set it in my classpath.
If anyone has any suggestions for how I could correct this error, I would be really grateful!
You have to put MySQL jdbc connector jar library into the classpath.
Then initialize the driver before opening the connection with code like the following :
Class.forName("com.mysql.jdbc.Driver").newInstance();
You will need the corresponding mysql JDBC driver jar in your classpath or loadable by your container. See the doc for ConnectorJ and note the installation instructions.
Try to add mysql-connector-java-5.1.20.jar to Glassfish (or Tomcat) lib folder.
you have also a error in this row
constat.executeQuery(query);
if you want insert some data in data base you have to use this code
constat.executeUpdate(query);

Categories

Resources