Keeping getting a Communications link failure and don't know why - java

I did search here and found some useful code to connect to a MySql db using SSH tunneling. I essentially copied the following code from another example, of course replacing it with my own credentials, but I keep getting the following error:
"com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: "
Code:
public void connect(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
Properties info = new Properties();
info.put("proxy_host", "proxyhost.com");
info.put("proxy_port", "22");
info.put("proxy_user", "username");
info.put("proxy_password", "password");
info.put("user", "user_qa");
info.put("password", "password");
conn = DriverManager.getConnection("jdbc:mysql://qa2-commerce-master:4417/commerce", info);
Statement stmt = conn.createStatement();
} catch (SQLException er) {
er.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
This is all I have as I just want to get the connection to work. Any help would be greatly appreciated. I copied the code exactly from here:
Connect to MySQL using JDBC driver through a proxy

Related

ClassNotFoundException: Google Cloud SQL with MySQL/SocketFactory

I'm trying to connect my Java code to a db I've created in Google Cloud SQL, but I'm getting ClassNotFound and SQLException errors: -
java.lang.ClassNotFoundException: com.google.cloud.sql.mysql.SocketFactory
java.sql.SQLException: No suitable driver found for jdbc:mysql
I'm also getting a NullPointerException in code, in the getAllFilms() method at the line below, which I'm assuming is because the code isn't making a db connection: -
ResultSet rs1 = stmt.executeQuery(selectSQL);
Things I've done so far: -
Tested the Google Cloud SQL db credentials, through a client connection
Reviewed related posts, particularly [this one][1]
Been through the Google documentation
Added MySQL and Socket Factory Connector(j8) JARs to my project dependencies
Unfortunately I'm still unable to resolve. Hopefully someone can help. I've attached my Java code below. Thanks in advance...
Film oneFilm = null;
Connection googleSqlConnection = null;
Statement stmt = null;
String url = "jdbc:mysql:///<dbname>?<cloudSqlInstance>&socketFactory=com.google.cloud.sql.
mysql.SocketFactory&user=<user>&password=<pword>";
public FilmDAO() {
}
private void openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.google.cloud.sql.mysql.SocketFactory");
} catch (Exception e) {
System.out.println(e);
}
try {
googleSqlConnection = DriverManager.getConnection(url);
stmt = googleSqlConnection.createStatement();
} catch (SQLException se) {
System.out.println(se);
}
}
private void closeConnection() {
try {
googleSqlConnection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<Film> getAllFilms() {
ArrayList<Film> allFilms = new ArrayList<>();
openConnection();
try {
String selectSQL = "select * from films limit 50";
ResultSet rs1 = stmt.executeQuery(selectSQL);
while (rs1.next()) {
oneFilm = getNextFilm(rs1);
allFilms.add(oneFilm);
}
stmt.close();
closeConnection();
} catch (SQLException se) {
System.out.println(se);
}
return allFilms;
}
[1]: https://stackoverflow.com/questions/53693679/connecting-to-google-cloud-sql-with-java
Have you added the Cloud SQL JDBC SocketFactory and mysql-connector-java to your pom.xml?

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.

DriverManager.getConnection(); How can I determine whether the username/password is wrong or the Driver is not able to connect to the database?

Here's my Code:
public static Connection connectToDataBase() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (final Exception e) {
throw new RuntimeException("Driver failure");
}
connectionProperties = new Properties();
connectionProperties.put("user", user);
connectionProperties.put("password", passwor);
datenbankverbindung = DriverManager.getConnection(link, connectionProperties);
return connection;
}
I'm connecting to the database, which works fine. But I want to know whether the login data are false or if there's a problem with the connection.
Please read this
It says that DriverManager.getConnection throws SQLException. So you can catch this exception like:
try{
...
datenbankverbindung = DriverManager.getConnection(link,connectionProperties);
}catch(SQLException e){
...//do whatever you want
}
Hope this helps.

DriverManager.getConnection cannot be resolved to a type

I am trying to connect a Java program to a database in localhost. My problem seems to be very simple, but I cannot find any answer.
When I try to compile, I get the following error:
DriverManager.getConnection cannot be resolved to a type
On the following code:
try{
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex){
System.out.println("Error found " + ex);
ex.printStackTrace();
}
// Here is where the error pops up
Connection connection = new DriverManager.getConnection("jdbc:mysql//localhost:3306/project3", "root", "root");
I am assuming I screwed up some installation, but I am not completely sure what.
Thank you for any help.
why new here?
Just use
DriverManager.getConnection("jdbc:mysql//localhost:3306/project3",
"root", "root");
getConnection() is static method. just call it as above.
Just Edit your code like this
try{
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex){
System.out.println("Error found " + ex);
ex.printStackTrace();
}
Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/project3", "root", "root");
Avoid new And put : after jdbc:mysql

Cant connect to specific schema in mysql

i'm trying to connect with jdbc to a specific schema in mysql server, the schema name is mining
when i'm trying to connect i get access to all the DB and therefore the executing statements apply to all the schemes in my db instead only to "mining"
this is how i establish a connection:
public class Mining {
Connection conn;
void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.conn = DriverManager.getConnection(
"jdbc:mysql://localhost/?currentSchema=mining","admin","admin" );
//I ALSO TRIED THIS: "jdbc:mysql://localhost/mining","admin","admin"
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
any thoughts?
thanks!
try,
private Connection connect = DriverManager
.getConnection("jdbc:mysql://localhost/mining?"
+ "user=admin&password=admin");
String databaseURL = jdbc:mysql://hostName:portNumber/schemaName?
Connection connectionObj = DriverManager.getConnection(databaseURL,userName,password);

Categories