JDBC connection error in mysql (ClassNotFoundException) [duplicate] - java

This question already has answers here:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse
(21 answers)
Closed 7 years ago.
Hey I am new to java and is right now learning about JDBC. Well i have written this code to create a connection to the sql server where my database is located :
import java.sql.*;
public class Mysql
{
public static void getmysqlconnection()
{
try
{
Connection con = null;
Class.forName("com.mysql,jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/EMP","root","password");
System.out.println("connection created");
}
catch(SQLException se)
{
System.out.println("SQl Exception" + se);
}
catch(ClassNotFoundException e)
{
System.out.println("ClassNotFoundException" + e);
}
}
public static void main(String args[])
{
getmysqlconnection();
}
}
But on compiling it is generating the following error :
ClassNotFoundExceptionjava.lang.ClassNotFoundException: com.mysql.jdbc.Driver

It seems you have a typo. The class name is com.mysql.jdbc.Driver not com.mysql,jdbc.Driver (dot instead of a comma). Also make sure the MySQL JDBC driver Jar is in the classpath. Otherwise the ClassNotFoundException is thrown.

Related

Unable to connect database to server [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 11 days ago.
Unable to connect Postgres database to Tomcat 10.0.27 server
Here is DBConnection code:
public class DBConnection {
public static Connection getConnectionToDatabase() {
Connection connection = null;
try {
System.out.println("MySQL JDBC Driver Registered!");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/hplus", "postgres", "");
}
catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
System.out.println("Connection made to DB!");
}
return connection;
}
}
Here is the code, where i try to get the connection:
public class ApplicationDao {
public List<Product> searchProducts(String searchString) {
Product product = null;
List<Product> products = new ArrayList<>();
try{
Connection connection = DBConnection.getConnectionToDatabase();
String sql = "select * from products where product_name like '%"+searchString+"%'";
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(sql);
while(set.next()){
product= new Product();
product.setProductId(set.getInt("product_id"));
product.setProductImgPath(set.getString("image_path"));
product.setProductName(set.getString("product_name"));
products.add(product);
}
}
catch(SQLException exception){
exception.printStackTrace();
}
return products;
}
}
Here is what i get:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Cannot invoke "java.sql.Connection.createStatement()" because "connection" is null
I tried to debug the code but got no response. I looked on different forms what the problem is, but I did not find anything
The problem was in incorrect driver. Everything work out after adding this lines of code in DBConnection class:
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// ...

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error in Java 10

Recently I wrote this code for connecting to MySQL in Eclipse, I am using Java 10 but I run this code I found. I add a sql.connector.jar file also into my class path but still same error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Code:
package ExamplePackage;
import java.sql.*;
import java.util.*;
public class ConnectionManager {
static Connection con;
static String url;
public static Connection getConnection()
{
try
{
String url = "jdbc:mysql://localhost:3306/new_schema.student";
// assuming "DataSource" is your DataSource name
//String connectionUrl = "jdbc:sqlserver://DESKTOP-05S6KIJ;databaseName=users;";
Class.forName("com.mysql.jdbc.Driver");
try
{
con = DriverManager.getConnection(url,"Shaik","Shaik#786");
// assuming your SQL Server's username is "username"
// and password is "password"
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
catch(Exception e)
{
System.out.println(e);
}
return con;
}
}
I think the issue is not in your project code, you need to add the com.mysql.jdb*.jar driver in your project.
The Class.forName("com.mysql.jdbc.Driver"); is trying to load the driver that is not found -> java.lang.ClassNotFoundException: com.mysql.jdbc.Driver .

java web app refuses to connect to SQL Database when deployed on Tomcat

So i am facing the following problem.
I have developed an web app that has the following connection to a SQL Server database. (db connection code attached)
public class DBConnection
{
private DatabaseMetaData dma;
private static Connection con;
private static DBConnection instance = null;
private static String security = "integratedSecurity=true;";
private DBConnection()
{
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} catch (Exception e) {
System.out.println("Can not find the driver");
System.out.println(e.getMessage());
}
try{
con = DriverManager.getConnection("jdbc:jtds:sqlserver://<Machine>;databaseName=<DBName>; useNTLMv2=true;");
//set autocommit
con.setAutoCommit(true);
dma = con.getMetaData(); // get meta data
System.out.println("Connection to " + dma.getURL());
System.out.println("Driver " + dma.getDriverName());
System.out.println("Database product name " + dma.getDatabaseProductName());
}
catch(Exception e){
System.out.println("Problems with the connection to the database");
System.out.println(e.getMessage());
System.out.println(con);
}
}
public static void closeConnection()
{
try{
con.close();
System.out.println("The connection is closed");
}
catch (Exception e){
System.out.println("Error trying to close the database " + e.getMessage());
}
}
public Connection getDBcon()
{
return con;
}
public static DBConnection getInstance()
{
if (instance == null)
{
instance = new DBConnection();
}
return instance;
}
public static void startTransaction()
{ try{
con.setAutoCommit(false);
}
catch(Exception e){
System.out.println("fail start transaction");
System.out.println(e.getMessage());
}
}
public static void commitTransaction()
{ try{
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail commit transaction");
System.out.println(e.getMessage());
}
}
public static void rollbackTransaction()
{
try
{
con.rollback();
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail rollback transaction");
System.out.println(e.getMessage());
}
}
I am using a Tomcat 8 on InteliJ IDE for running the app and debugging. Which works fine. (DB connection is established)
The problem is that when i take the war file and deploy it in the same Tomcat Server i get no DB Connection. (No DB connection)
I have checked all the .jar files in the tomcat and the project and I have added all the needed files.
Can't seem to find what is causing this issue. Maybe there is someone who got stuck with the same issue
I can't get a proper undertanding what is causing this issue and how to fix it
**EDIT: Following I have added the error displayed when trying to load data
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is java.lang.NullPointerException
root cause
java.lang.NullPointerException
com.lifeletapp.business.dataLayer.DbLogIn.isValidUser(DbLogIn.java:27)
com.lifeletapp.business.HelloController.verifyLogin(HelloController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
DbLogin class:
public class DbLogIn implements ILogIn
{
private Connection conn;
public DbLogIn()
{
conn = DBConnection.getInstance().getDBcon();
}
public Staff isValidUser(String userName, String password)
{
Staff staff = new Staff();
try {
String query = "SELECT * FROM Staff WHERE userName=? AND pass=?";
PreparedStatement preparedStatement = conn.prepareStatement( query );
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
while( resultSet.next() ) {
staff.setUserID(resultSet.getInt("userID"));
staff.setfName(resultSet.getString("fName") );
staff.setlName(resultSet.getString("lName") );
staff.setUserName(resultSet.getString("userName") );
staff.setPass(resultSet.getString("pass") );
staff.setEmail(resultSet.getString("email") );
}
resultSet.close();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return staff;
}
}
This is more a config or server issue. Not a code issue.
As mentioned in the comments I have tested if var conn == null -> resulted true. And the connection dose not get nulled anywhere. Please view code. Then again the above code works when run from the InteliJ debugger.
So finally figured out what was the issue.
Why was it working on my IDE config:
1. I was using java JDK 1.7 as JAVA_HOME
2. I was using an older version of Tomcat as a build
3. In order to work with JDTS you need to extract the nlmauth.dll from the .jar archive and copy it to the configured env JDK(jdk1.7-->>bin->>copy here)
Why was it not working on Tomcat server:
1.I was using Tomcat 8.xxx
2.Tomcat 8.xx require JDk 8
3. In the JDK 8 i have not past the nlmauth.dll ( once i have done this everything was working)
In order to approach this issue the first clue will be looking into the tomcat server logs.
On my presumption this issue is prom to occur only when you have an Database connection establish via Integrated Security.
My presumption is related to the fact that in the tomcat log the main error that was denying the JDBC driver was based on the integrated security credentials.
Best of luck to you all out there.

Class.forName("oracle.jdbc.driver.OracleDriver"); throwing NullPointerException

Class.forName("oracle.jdbc.driver.OracleDriver");
is throwing NullPointerException, I have tried a lot to solve it but failed.
You can check following function where the problem is occuring:
public static Connection con=null;
public static Connection getOracleConnection()
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe",Constants.OracleUsername,Constants.OraclePassword);
}catch(NullPointerException npe){ npe.printStackTrace(); }
catch(Exception e){ System.out.println("Error to create the connection "); }
return con;
}
Check that the Oracle JDBC driver is in your classpath.
You can find one on the page below if not yet downloaded:
http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html

Simple Java web service connecting to mySql not working [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I decided to try to connect a java client to a mysql db running on wamp.
Can anybody tell me why im getting this runtime problem?
My DBConnect() class
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DbConnect {
private Connection conn;
private Statement statement;
private ResultSet resultset;
public DbConnect(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://xxx.xxx.xxx.xxx:3306/pk","root","");
} catch (Exception e){
System.out.println("Error: " + e);
}
}
public String getData(){
String result ="";
try {
resultset = statement.executeQuery("select * from data_user");
while(resultset.next())
{
result+=resultset.getString("userFirstName");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
My main() class
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
DbConnect conn = new DbConnect();
System.out.println(conn.getData());
}
My error at runtime
Error: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
The last packet sent successfully to the server was 0 milliseconds
ago. The driver has not received any packets from the server.
Exception in thread "main" java.lang.NullPointerException at
DbConnect.getData(DbConnect.java:26) at Main.main(Main.java:8) ERROR:
JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [util.c:840]
}
Offending line
resultset = statement.executeQuery("select * from data_user");
It looks like you didnt instantiate your statement, unless you are missing some code. You need to do something like the following: statement=conn.createStatement();
Take a look at this example

Categories