MySQL connection does not work I get error [duplicate] - mysql

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)

Related

Using MySQL instead of H2

When I try to test a simple REST Service, to output the number of users in a web page, it gives a lot of errors. I'm using MySQL and while testing JPA Query in the console, I get the right answer. But when I try from the web page, it gives this errors:
01:07:43,647 WARN [org.jboss.as.weld] (default task-1) WFLYWELD0052:
Using deployment classloader to load proxy classes for module
org.jboss.jts. Package-private access will not work. To fix this the
module should declare dependencies on [org.jboss.weld.core,
org.jboss.weld.spi] 01:07:43,731 INFO
[org.hibernate.hql.internal.QueryTranslatorFactoryInitiator] (default
task-1) HHH000397: Using ASTQueryTranslatorFactory 01:07:43,801 WARN
[org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-1)
SQL Error: 42102, SQLState: 42S02 01:07:43,802 ERROR
[org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-1)
Table "USERS" not found; SQL statement: select count(users0_.id) as
col_0_0_ from users users0_ [42102-193] 01:07:43,807 ERROR
[io.undertow.request] (default task-1) UT005023: Exception handling
request to /amd-project-1.0/api/users/count:
org.jboss.resteasy.spi.UnhandledException:
javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not prepare
statement at
org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:78)
at
org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:222)
at
org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:193)
at
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:455)
at
org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:229)
at
org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:135)
at
org.jboss.resteasy.core.interception.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:355)
at
org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:138)
at
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:215)
at
org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:227)
at
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
at
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:791) at
io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at
io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at
io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:55)
at
io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at
io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at
io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at
io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at
io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at
io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at
org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at
io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at
io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at
io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at
io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at
io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at
io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at
io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at
io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at
org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at
org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at
io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at
io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at
io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at
io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at
io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at
io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at
io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at
org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at
org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at
org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at
org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at
org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at
org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1502)
at
io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at
io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at
io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at
io.undertow.server.Connectors.executeRootHandler(Connectors.java:360)
at
io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at
org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at
org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1985)
at
org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1487)
at
org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1378)
at java.lang.Thread.run(Thread.java:748) Caused by:
javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not prepare
statement at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at
org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at
org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1514)
at
org.hibernate.query.internal.AbstractProducedQuery.getSingleResult(AbstractProducedQuery.java:1553)
at
org.jboss.as.jpa.container.TypedQueryNonTxInvocationDetacher.getSingleResult(TypedQueryNonTxInvocationDetacher.java:69)
at
com.oraldveizi.amdproject.repository.UsersRepository.countAll(UsersRepository.java:36)
at
com.oraldveizi.amdproject.repository.UsersRepository$Proxy$_$$WeldSubclass.countAll$$super(Unknown
Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.jboss.weld.interceptor.proxy.TerminalAroundInvokeInvocationContext.proceedInternal(TerminalAroundInvokeInvocationContext.java:51)
at
org.jboss.weld.interceptor.proxy.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:78)
at
com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.invokeInNoTx(TransactionalInterceptorBase.java:195)
at
com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorSupports.doIntercept(TransactionalInterceptorSupports.java:53)
at
com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:88)
at
com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorSupports.intercept(TransactionalInterceptorSupports.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.jboss.weld.interceptor.reader.SimpleInterceptorInvocation$SimpleMethodInvocation.invoke(SimpleInterceptorInvocation.java:73)
at
org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeAroundInvoke(InterceptorMethodHandler.java:84)
at
org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.executeInterception(InterceptorMethodHandler.java:72)
at
org.jboss.weld.interceptor.proxy.InterceptorMethodHandler.invoke(InterceptorMethodHandler.java:56)
at
org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:79)
at
org.jboss.weld.bean.proxy.CombinedInterceptorAndDecoratorStackMethodHandler.invoke(CombinedInterceptorAndDecoratorStackMethodHandler.java:68)
at
com.oraldveizi.amdproject.repository.UsersRepository$Proxy$$$WeldSubclass.countAll(Unknown
Source) at
com.oraldveizi.amdproject.endpoints.UsersEndpoint.countUsers(UsersEndpoint.java:41)
at
com.oraldveizi.amdproject.endpoints.UsersEndpoint$Proxy$$$WeldClientProxy.countUsers(Unknown
Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:139)
at
org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:509)
at
org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:399)
at
org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$0(ResourceMethodInvoker.java:363)
at
org.jboss.resteasy.core.interception.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:355)
at
org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:365)
at
org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:337)
at
org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:310)
at
org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:439)
... 56 more Caused by: org.hibernate.exception.SQLGrammarException:
could not prepare statement at
org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at
org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
at
org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
at
org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1984)
at
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1914)
at
org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1892)
at org.hibernate.loader.Loader.doQuery(Loader.java:937) at
org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340)
at org.hibernate.loader.Loader.doList(Loader.java:2689) at
org.hibernate.loader.Loader.doList(Loader.java:2672) at
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506) at
org.hibernate.loader.Loader.list(Loader.java:2501) at
org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:504) at
org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:395)
at
org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1508) at
org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1537)
at
org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505)
... 96 more Caused by: org.h2.jdbc.JdbcSQLException: Table "USERS"
not found; SQL statement: select count(users0.id) as col_0_0_ from
users users0_ [42102-193] at
org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179) at
org.h2.message.DbException.get(DbException.java:155) at
org.h2.command.Parser.readTableOrView(Parser.java:5389) at
org.h2.command.Parser.readTableFilter(Parser.java:1257) at
org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1897) at
org.h2.command.Parser.parseSelectSimple(Parser.java:2045) at
org.h2.command.Parser.parseSelectSub(Parser.java:1891) at
org.h2.command.Parser.parseSelectUnion(Parser.java:1709) at
org.h2.command.Parser.parseSelect(Parser.java:1697) at
org.h2.command.Parser.parsePrepared(Parser.java:445) at
org.h2.command.Parser.parse(Parser.java:317) at
org.h2.command.Parser.parse(Parser.java:289) at
org.h2.command.Parser.prepareCommand(Parser.java:254) at
org.h2.engine.Session.prepareLocal(Session.java:561) at
org.h2.engine.Session.prepareCommand(Session.java:502) at
org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1203)
at
org.h2.jdbc.JdbcPreparedStatement.(JdbcPreparedStatement.java:73)
at
org.h2.jdbc.JdbcConnection.prepareStatement(JdbcConnection.java:676)
at
org.jboss.jca.adapters.jdbc.BaseWrapperManagedConnection.doPrepareStatement(BaseWrapperManagedConnection.java:758)
at
org.jboss.jca.adapters.jdbc.BaseWrapperManagedConnection.prepareStatement(BaseWrapperManagedConnection.java:744)
at
org.jboss.jca.adapters.jdbc.WrappedConnection.prepareStatement(WrappedConnection.java:459)
at
org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
at
org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import java.util.List;
import static javax.transaction.Transactional.TxType.REQUIRED;
import static javax.transaction.Transactional.TxType.SUPPORTS;
#Transactional(SUPPORTS)
public class UsersRepository implements EntityInterface<Users, Long> {
#PersistenceContext(name = "projectPU")
private EntityManager entityManager;
public Users find(Long id) {
return entityManager.find(Users.class, id);
}
public List<Users> findAll() {
Query query = entityManager.createNativeQuery("SELECT u FROM Users u ORDER BY u.username DESC");
List<Users> usersList = query.getResultList();
return usersList;
}
public Long countAll() {
TypedQuery<Long> query = entityManager.createQuery(
"SELECT COUNT(u) FROM Users u", Long.class);
return query.getSingleResult();
}
#Transactional(REQUIRED)
public Users create(Users users) {
entityManager.persist(users);
return users;
}
public void delete(Long id) {
entityManager.remove(entityManager.getReference(Users.class, id));
}
}
This is my UserRepository.java
and this is UserEndpoint.java
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.List;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN;
#Path("/users")
public class UsersEndpoint {
#Inject
private UsersRepository usersRepository;
public Users find(Long id) {
return usersRepository.find(id);
}
#GET
#Produces("text/html")
public Response getUsers() {
List<Users> usersList = usersRepository.findAll();
if(usersList.size() == 0)
return Response.status(Response.Status.NO_CONTENT).build();
return Response.ok(usersList).build();
}
#GET
#Path("/count")
#Produces(TEXT_PLAIN)
public Response countUsers() {
Long numberOfUsers = usersRepository.countAll();
if(numberOfUsers == 0)
return Response.status(Response.Status.NO_CONTENT).build();
return Response.ok(numberOfUsers).build();
}
I don't have hibernate.cfg.xml, because i have inserted the data source from the Configuration Menu. How can I change to use MySQL instead of H2?

not able to connect to RedHat Openshift MySQL via JDBC

I've added a MySQL 5.5 cartridge on my RedHat openshift account within my openshift application. I've written the following Java program using JDBC, to connect to this MySQL database:
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
public class DBConnect {
public static void main(String[] args) {
String email = args[0];
String password = args[1];
try {
Class.forName("com.mysql.jdbc.Driver");
//Connection con = DriverManager.getConnection("jdbc:mysql://127.5.11.2:3306/funchat", "adminLvAZEDC", "G6Sm_Fl6C9A3");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from users where Email = '" + email + "' and Password = '" + password + "'");
if (rs.next()) {
System.out.println("Login Successful");
} else {
System.out.println("Login failed");
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
I think, the parameters to the call DriverManager.getConnection are correct. I'm running this program remotely from a Windows 10 workstation. I'm getting following error when I run this program:
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.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:989)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:341)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2203)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2236)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2035)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:790)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnect.main(DBConnect.java:12)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
... 15 more
Can someone please help me, to solve this problem?

Why can I not click on a blank area with chrome?

I wanted to learn how to click on a blank area on a page using selenium. The commonly suggested method is to click the html element. This method fails with chrome, but not with firefox. Why does this happen and how do I fix it ?
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Temp {
private static final WebDriver browser = new ChromeDriver();
private static String url = "https://www.google.com/";
public static void main(String[] args) {
browser.get(url);
browser.findElement(By.tagName("html")).click();
}
}
Exception:
Starting ChromeDriver (v2.9.248315) on port 15072
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.
(Session info: chrome=52.0.2743.116)
(Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 334 milliseconds
Session ID: 69ce4de350c6ade8abcbcd0b1b2093f6
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:327)
at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:85)
at src.Temp.main(Temp.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

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).

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

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.