mysql connectivity issue: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver - mysql

I am attemping to establish Mysql connectivity to Database using Java Struts1. Here the code snippet.Also I added mysql-connector-java-5.0.8-bin.jar to web-inf/lib folder .
Also added the same to classpath variable.
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class select {
public void connection() {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}.
This is Error message. What steps am I missing. Kindly suggest ASAP.
-------- MySQL JDBC Connection Testing ------------
Where is your MySQL JDBC Driver?
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Com.Candidjava.select.connection(select.java:14)
at Com.Candidjava.LoginAction.execute(LoginAction.java:26)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:643)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)

Add mysql-connector-java-5.0.8-bin.jar to your tomcat installation directory as well. And when right click on your project and select build path then libraries. and inside libraries Apache Tomcat you should find your connector jar then only your mysql will work

try this is an example of jdbc connection to mysql database:
import java.sql.DriverManager;
public class Connection {
private static java.sql.Connection conex = null;
public static java.sql.Connection getConnectionInstance() {
if (conex == null) {
try {
// connection to database
Class.forName("com.mysql.jdbc.Driver");
conex = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/databaseName","root",
"MySQLPassword");
return conex;
} catch (Exception e) {
}
}
return conex;
}
}
make sure you have opened the port selected during install.

Related

Why Spring Mvc application with Hibernate throw an error: Unable to acquire JDBC Connection

I followed the tutorial on the following link:Tutorial Spring MVC, and I used Ubunto, MySQL and Eclipse, but at runtime I received an error, below the trace of the error:
Root Cause
org.springframework.transaction.CannotCreateTransactionException:
Could not open Hibernate Session for transaction; nested exception is
org.hibernate.exception.JDBCConnectionException: Unable to acquire
JDBC Connection
org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:541)
org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
org.o7planning.springmvcforms.controller.MyController$$EnhancerBySpringCGLIB$$32fb6e31.applicantList()
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:568)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
And below the config properties file:
# DataSource
ds.database-driver=com.mysql.jdbc.Driver
ds.url=jdbc:mysql://localhost:3306/my_databse?autoReconnect=true&useSSL=false
ds.username=root
ds.password=mypassword
# Hibernate Config
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
current_session_context_class=thread
And below the function used for configuration of Hibernate:
#Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("ds.database-driver"));
dataSource.setUrl(env.getProperty("ds.url"));
dataSource.setUsername(env.getProperty("ds.username"));
dataSource.setPassword(env.getProperty("ds.password"));
return dataSource;
}
And here is the function to create session Factory object:
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource)throws Exception {
Properties properties = new Properties();
// See: ds-hibernate-cfg.properties
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
properties.put("current_session_context_class", env.getProperty("current_session_context_class"));
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setPackagesToScan(new String[] { "org.o7planning.springmvcforms.entity" });
factoryBean.setDataSource(dataSource);
factoryBean.setHibernateProperties(properties);
factoryBean.afterPropertiesSet();
//
SessionFactory sf = factoryBean.getObject();
return sf;
}
What is the source of this error?
I found the solution, for those who encounter the same problem.
Indeed the version of Mysql is 8.0.28,for this reason it is necessary to use the version 8.0.11 of Mysql connector and to use the configuration of driver under the bellow format:
ds.database-d=com.mysql.cj.jdbc.Driver
instead of
ds.database-d=com.mysql.jdbc.Driver
Hoping it can help

MySQL connection does not work I get error [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse
(21 answers)
runtime error: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
(6 answers)
Closed 4 years ago.
So I want to retrieve one row of the table but first I want to make it works and then I will do the rest, so below is the code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.*;
import java.util.*;
import java.sql.*;
public class ExampleForDB {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/******","*****","******");
System.out.print("Successful connection with MySQL!");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select Number1 from lottery1955-00 where id=1");
System.out.println(rs.getInt(1)+" "+rs.getString(1));
con.close();
}catch (SQLException e ) {
e.printStackTrace();
}
}
}
And here you can see my error I tried so many different ways that I found here in StackOverflow but none of them worked for me, can you share your experience?
see the error below
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at ExampleForDB.main(ExampleForDB.java:16)

java.io.EOFException,SSH port forwarding

package com.soul.db;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import java.sql.Connection;
public class JdbcSSHConnection {
/**
* Java Program to connect to remote database through SSH using port forwarding
* #throws SQLException
*/
public static void main(String[] args) throws SQLException {
int lport=443;
String rhost="10.99.69.10";
String host="10.105.27.201";
int rport=3306;
String user="root";
String password="SysPassword1";
String dbuserName = "root";
String dbpassword = "DBPassword1";
String url = "jdbc:mysql://localhost:"+lport+"/proj_db";//"jdbc:mysql://localhost:3306", "root", "mysql"
String driverName="com.mysql.jdbc.Driver";
Connection conn = null;
Session session= null;
try{
//Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
int assinged_port=session.setPortForwardingL(lport,rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
System.out.println("Port Forwarded");
//mysql database connectivity
Class.forName(driverName).newInstance();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection (url, "root", "DBPassword1");
// step3 create the statement object
Statement stmt = conn.createStatement();
System.out.println ("Database connection established");
// step4 execute query
ResultSet rs = stmt.executeQuery("select DISTINCT STUD_NAME from STUD_DETAILS;");
while (rs.next())
System.out.println(rs.getString(1));
// step5 close the connection object
conn.close();
//System.out.println ("Database connection established");
// System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null && !conn.isClosed()){
System.out.println("Closing Database Connection");
conn.close();
}
if(session !=null && session.isConnected()){
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
}
}
I installed SSH secure shell client on my windows machine.I am trying to connect mysql server installed in linux machine.
Now i am getting below Error:
Connected
localhost:443 -> 10.99.69.10:3306
Port Forwarded
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
com.mysql.jdbc.CommunicationsException
MESSAGE: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.io.EOFException
MESSAGE: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
STACKTRACE:
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1997)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:573)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1044)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775)
at com.mysql.jdbc.Connection.(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.soul.db.JdbcSSHConnection.main(JdbcSSHConnection.java:54)
** END NESTED EXCEPTION **
Last packet sent to the server was 0 ms ago.
STACKTRACE:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.io.EOFException
MESSAGE: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
STACKTRACE:
java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1997)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:573)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1044)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775)
at com.mysql.jdbc.Connection.(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.soul.db.JdbcSSHConnection.main(JdbcSSHConnection.java:54)
** END NESTED EXCEPTION **
Last packet sent to the server was 0 ms ago.
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:641)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1044)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775)
at com.mysql.jdbc.Connection.(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.soul.db.JdbcSSHConnection.main(JdbcSSHConnection.java:54)
** END NESTED EXCEPTION **
Last packet sent to the server was 0 ms ago.
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2847)
Closing SSH Connection
at com.mysql.jdbc.Connection.(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.soul.db.JdbcSSHConnection.main(JdbcSSHConnection.java:54)
These errors were resolved for me once I started using the hostname instead of the IP address for the SSH tunnel. I am also connecting to MySQL on Linux via SSH tunnel (with DataGrip IDE).

JDBC Connection error persists

I am using MySQL Workbench (5.6.19). It has several connections among which the table that i want to access is in "Connection1"(name of connection). Connection Host: 122.0.0.0 . My database name is "sorder". user = "root", password = "password",port = 3306.
Here's my piece of code:
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("Driver Connection Failed.");
e.printStackTrace();
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try
{
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sorder","root", "password");
} catch (SQLException e)
{
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
My driver connection failed. Plus i am not sure what my path Strin url should be since there are more than 1 connections in mySQL workbench.
error :
-------- MySQL JDBC Connection Testing ------------
Driver Connection Failed.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:126)
at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:63)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at org.apache.jsp.NewFile_jsp._jspService(NewFile_jsp.java:65)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
I followed whatever suggestions i got in different forums, like:
reassured that JAR file is there in build path.
reassured that JAR file is there in Window>Prefernces>Java>Build Path>Classpath variable
JAR file explicitily in WEB-INF/lib buildpath.
Thankful for any suggestions.
Regards.
when we manually created a xml file and added welcome-file-list, it worked. Default xml file was missing.

Why am I getting "Data source name not found and no default driver specified"?

From Java, I want to connect to an .ACCDB file in the server (DSN less) and I keep getting the error. I googled for few hours and could not find anything. Please help!
String sURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=DBQ=C:/test/theDB.accdb;READONLY=true;";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
log.debug("url: "+sURL);
// create connection to database using connection string
dbCon = DriverManager.getConnection(sURL);
}
catch(SQLException e) {
//retry
try{dbCon = DriverManager.getConnection(sURL);}
catch(SQLException ex){
// Now, it is real failing. Throw exception
log.error("Fail second time",ex);
throw new SQLException(e.getMessage());
}
} catch (ClassNotFoundException e) {
log.error(e.getMessage());
throw new SQLException(e.getMessage());
}
return dbCon;
Here's the exception I get:
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source) [na:1.7.0_10] at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source) [na:1.7.0_10] at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source) [na:1.7.0_10] at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source) [na:1.7.0_10] at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source) [na:1.7.0_10] at java.sql.DriverManager.getConnection(Unknown Source) [na:1.7.0_10] at java.sql.DriverManager.getCon...
DBQ=DBQ=C: ... will probably cause problems. One DBQ= is sufficient.