JDBC Connection error persists - mysql

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.

Related

Unable to connect to MySQL Database with Java through SSH

I know that there are many questions regarding this problem already, and believe me I've looked through all of them.
Some background, I'm using IntelliJ and I've been able to both connect to the database with IntelliJ's data source tool and I've been able to SSH into the server itself using the terminal. For some reason, even if I try to do the same thing with Java it doesn't work. Here's my code:
String serverIP = "123.45.67.890"
String username = "root";
String password = "password";
// Establish SSH tunnel with server if not running locally
try {
if (!Inet4Address.getLocalHost().getHostAddress().equals(ServerIP) {
System.out.println("Remote connection detected.");
System.out.println("Establishing SSH Tunnel...");
JSch jSch = new JSch();
Session session = jSch.getSession(username, ServerIP, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
System.out.printf("Connecting to remote server at %s...\n", ServerIP);
session.connect();
System.out.println("Connected!");
session.setPortForwardingL(3306, ServerIP, 3306);
}
} catch (Exception e) {
e.printStackTrace();
}
// Load mySQL Driver
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
String url = String.format("jdbc:mysql://%s:3306/db_name", ServerIP);
// Connect to database
System.out.println("Connecting to database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
this.connection = connection;
} catch (SQLException e) {
this.connection = null;
throw new IllegalStateException("Cannot connect to database!", e);
}
And here's the error I get:
Remote connection detected.
Establishing SSH Tunnel...
Connecting to remote server at 123.45.67.890...
Connected!
Loading driver...
Driver loaded!
Connecting to database...
java.lang.IllegalStateException: Cannot connect to database!
...
a bunch of crap
...
Caused by: java.sql.SQLException: null, message from server: "Host 'my.personal.computer.local.hostname' is not allowed to connect to this MySQL server"
...
a bunch more crap
...
It seems to me like for some reason, the Java code isn't using the SSH tunnel I put so much effort into copying StackOverflow code to make, and is instead rudely trying to connect normally. What am I doing wrong?
Some more info: The server itself is configured to listen for SQL on 0.0.0.0 and I also set the firewall to accept connections on port 3306.
Edit for clarity: I understand that I can probably fix this by giving my local computer privileges on the server, but I want to be able to connect through SSH.
Solution by OP.
The reason SSH wasn't working was because I needed to use a local open port, connect to SQL through that, then forward that to the remote port 3306. Also, I needed to port forward through localhost, not the server address.
(That is, change the session.setPortForwardingL(3306, ServerIP, 3306); line to session.setPortForwardingL(some-open-port, "localhost", 3306); and "jdbc:mysql://%s:3306/db_name" to "jdbc:mysql://%s:same-open-port/db_name".

MySQL JDBC Datasource lookup fails after updating to mysql-connector-java-5.1.44

Consider following code snippet:
try
{//try to connect
conn = DatasourceProvider.getDatasource("java:comp/env/jdbc/mysql/my_db").getConnection();
}
catch(Exception ex)
{//failed to acquire connection from the pool, retry
ex.printStackTrace();
}
When I run it with mysql-connector-java-5.1.10-bin.jar loaded in tomcat 8.5 it works gracefully, but when I update to mysql-connector-java-5.1.44-bin.jar it throws following exception:
javax.naming.NameNotFoundException: Name [jdbc/mysql/my_db] is not bound in this Context. Unable to find [jdbc].
at org.apache.naming.NamingContext.lookup(NamingContext.java:816)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
at org.apache.naming.NamingContext.lookup(NamingContext.java:173)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
This happens on both MySQL5.6 and MySQL5.7.
Any Idea?

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

connecting to MySQL using JDBC in eclipse

So I want to create a JDBC connection to MySQL server that is installed on my pc, here are the steps,
I installed MySQL with the username and password "root", downloaded mysql-connector-java and from theere I coped the JAR "mysql-connector-java-5.1.12-bin" to "C:\Sun\SDK\jdk\jre\lib\ext", I then added it as an external JAR in my project in eclipse, now in my class I have this code:
public void initialiseDatabase()
{
try {
// Load the Driver class.
Class.forName("com.mysql.jdbc.Driver");
//Create the connection using the static getConnection method
databaseConnection = DriverManager.getConnection (databaseUrl+databaseName,
dbUserName, dbPassword);
sqlStatement = databaseConnection.createStatement();
}
catch (SQLException e) {e.printStackTrace();}
catch (Exception e) {e.printStackTrace();}
}
(this is going to be psuedocode cause I am reading from a properties file and don't want the one helping me reading through long lines of code from main to figure out all the variables),
where databaseUrl = "127.0.0.1"
dbUserName = "root"
dbPassword = "root"
databaseName = "MySQL" //this one I am not sure of, do I need to create it or is it set inherenrly?
now the MySQL server is up and running, but when I call the method initialiseDatabase the following exception is thrown:
"java.sql.SQLException: No suitable driver found for rootroot
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Proxy$JDBCConnection.initialiseDatabase(Proxy.java:721)"
when line 721 is:
sqlStatement = databaseConnection.createStatement();
Where have I gone wrong?
thanks
Your database url should look like this:
jdbc:mysql://host:port/database
Example, if you use localhost, the default port and a database named cachedb, your url would be:
jdbc:mysql://localhost/cachedb

How to resolve this Exception : Data source rejected establishment of connection, message from server: "Too many connections"

I am using Hibernate 3 +Mysql 5.1 and after 98 insertion i am getting this Exception :
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
My hibernate.cfg.xml file is :
com.mysql.jdbc.Driver
jdbc:mysql://localhost/xml
root
root
10
false
org.hibernate.dialect.MySQLDialect
update
true
Do you close your connections in a finally block?
something like this?
Session sess = factory.openSession();
Transaction tx;
try {
tx = sess.beginTransaction();
//do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
sess.close();
}
If you don't you will be running out of connections.
I'd guess your application is leaking connections (opens them without properly closing them).