JDBC connection timed out on Windows 10 - java

This is my code:
public static void main(String[] args) {
System.out.println("Start");
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
Properties properties = new Properties();
properties.put("user", "xxx");
properties.put("password", "xxx");
Connection conn = DriverManager.getConnection("jdbc:db2://xxx.xxx.xxx.xxx:50000/xxxxxx", properties);
Statement stmt = conn.createStatement();
String query = "SELECT DESC_UFF FROM UFFICIO";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("DESC_UFF"));
}
conn.close();
System.out.println("Stop");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
I use a jar file and it works fine on Windows XP and Windows 7, on a different PC, but not on Windows 10.
On Windows 10 I have this error:
Start
com.ibm.db2.jcc.am.DisconnectNonTransientConnectionException: [jcc][t4][2043][11550][4.14.146] Eccezione java.net.ConnectException: errore durante l'apertura del socket sul server /xxx.xxx.xxx.xxx sulla porta 50.000 con il messaggio Connection timed out: connect. ERRORCODE=-4499, SQLSTATE=08001
at com.ibm.db2.jcc.am.ed.a(ed.java:320)
at com.ibm.db2.jcc.am.ed.a(ed.java:338)
at com.ibm.db2.jcc.t4.wb.a(wb.java:434)
at com.ibm.db2.jcc.t4.wb.<init>(wb.java:93)
at com.ibm.db2.jcc.t4.a.b(a.java:354)
at com.ibm.db2.jcc.t4.b.newAgent_(b.java:2030)
at com.ibm.db2.jcc.am.Connection.initConnection(Connection.java:732)
at com.ibm.db2.jcc.am.Connection.<init>(Connection.java:680)
at com.ibm.db2.jcc.t4.b.<init>(b.java:334)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:233)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:199)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:475)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:116)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at main.TestDb2.main(TestDb2.java:20)
Caused by: java.net.ConnectException: Connection timed out: 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.ibm.db2.jcc.t4.w.run(w.java:49)
at java.security.AccessController.doPrivileged(Native Method)
at com.ibm.db2.jcc.t4.wb.a(wb.java:420)
... 13 more
The version of DB2 database is 9.7 and Windows firewall is disabled.
Any suggestion?

Related

Java SQL expected 6 bytes and received 0 error

I am getting this error: "Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated." When I try to connect to my data base. I can not seem to find any solution that works. Could you guys give me a hand?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class RetrieveData
{
private String zone;
private String date;
private String userName = "User";
private String password = "Password";
private String serverAdress= "jdbc:derby://Server:1010/Database";
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;
RetrieveData(String zoneToPull, String dayToPull)
{
zone = zoneToPull;
date = dayToPull;
}
public int HistoryActual()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(serverAdress, userName, password);
String sql = "SELECT TOP 10 " +
"*" +
"FROM" +
"walks" +
"WHERE"+
"company_id = 'TMS3'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next())
{
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
return 0;
}
}
Here is the stack trace:
java.sql.SQLNonTransientConnectionException: Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated.
at org.apache.derby.client.am.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at RetrieveData.HistoryActual(RetrieveData.java:27)
at BookToGoals.(BookToGoals.java:34)
at Console.Console(Console.java:96)
at Console.access$0(Console.java:47)
at Console$1.run(Console.java:43)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: ERROR 08006: Insufficient data while reading from the network - expected a minimum of 6 bytes and received only 0 bytes. The connection has been terminated.
at org.apache.derby.client.net.Reply.fill(Unknown Source)
at org.apache.derby.client.net.Reply.ensureALayerDataInBuffer(Unknown Source)
at org.apache.derby.client.net.Reply.readDssHeader(Unknown Source)
at org.apache.derby.client.net.Reply.startSameIdChainParse(Unknown Source)
at org.apache.derby.client.net.NetConnectionReply.readExchangeServerAttributes(Unknown Source)
at org.apache.derby.client.net.NetConnection.readServerAttributesAndKeyExchange(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowServerAttributesAndKeyExchange(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowUSRIDPWDconnect(Unknown Source)
at org.apache.derby.client.net.NetConnection.flowConnect(Unknown Source)
at org.apache.derby.client.net.NetConnection.(Unknown Source)
at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl.newNetConnection(Unknown Source)
... 22 more
It looks like I found out what is going on. It is due to my own confusion. I am trying to connect to a Microsoft SQL database. Thus I need the sqljdbc driver not derby. This has resolve my issue. Thanks for the help guys.

How to connect MS Access database with Java 8?

What I am trying to do:
I want to connect my MS Access Database with Java 8. So I am using "UcanAccess" driver to connect to my Database.
What I am using:
Eclipse, Java 8, and MS Access database
My MS Access database path:
C:/Users/dave/My_WorkSpace/Eclipse_Workspaces/workspace-jsp/Database11.accdb"
I have the following Jar files in my project:
mysql-connector-java-5.1.35-bin.jar
ucanaccess-2.095.jar
jackcess-2.1.2.jar
hsqldb.jar
commons-lang3-3.4.jar
commons-logging-1.2.jar
Error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/builder/CompareToBuilder
at com.healthmarketscience.jackcess.impl.RowIdImpl.compareTo(RowIdImpl.java:106)
at com.healthmarketscience.jackcess.impl.IndexData$Entry.compareTo(IndexData.java:2039)
at com.healthmarketscience.jackcess.impl.IndexData$Entry.compareTo(IndexData.java:1847)
at java.util.Collections.indexedBinarySearch(Unknown Source)
at java.util.Collections.binarySearch(Unknown Source)
at com.healthmarketscience.jackcess.impl.IndexData$DataPage.findEntry(IndexData.java:2570)
at com.healthmarketscience.jackcess.impl.IndexData.findEntryPosition(IndexData.java:844)
at com.healthmarketscience.jackcess.impl.IndexData.access$3700(IndexData.java:47)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.updatePosition(IndexData.java:2335)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.restorePosition(IndexData.java:2273)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.restorePosition(IndexData.java:2256)
at com.healthmarketscience.jackcess.impl.IndexData$EntryCursor.beforeEntry(IndexData.java:2218)
at com.healthmarketscience.jackcess.impl.IndexCursorImpl.findPotentialRow(IndexCursorImpl.java:376)
at com.healthmarketscience.jackcess.impl.IndexCursorImpl.findFirstRowByEntryImpl(IndexCursorImpl.java:282)
at com.healthmarketscience.jackcess.impl.IndexCursorImpl.findFirstRowByEntry(IndexCursorImpl.java:153)
at com.healthmarketscience.jackcess.impl.DatabaseImpl$DefaultTableFinder.findRow(DatabaseImpl.java:2074)
at com.healthmarketscience.jackcess.impl.DatabaseImpl$TableFinder.findObjectId(DatabaseImpl.java:1953)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.readSystemCatalog(DatabaseImpl.java:858)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.<init>(DatabaseImpl.java:518)
at com.healthmarketscience.jackcess.impl.DatabaseImpl.open(DatabaseImpl.java:389)
at com.healthmarketscience.jackcess.DatabaseBuilder.open(DatabaseBuilder.java:248)
at net.ucanaccess.jdbc.DefaultJackcessOpener.open(DefaultJackcessOpener.java:38)
at net.ucanaccess.jdbc.DBReference.<init>(DBReference.java:158)
at net.ucanaccess.jdbc.DBReferenceSingleton.loadReference(DBReferenceSingleton.java:57)
at net.ucanaccess.jdbc.UcanaccessDriver.connect(UcanaccessDriver.java:103)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at ex01.main(ex01.java:37)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.builder.CompareToBuilder
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
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)
... 28 more
code to connect to database:
public class ex01 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess://C:/Users/dave/My_WorkSpace/Eclipse_Workspaces/workspace-jsp/Database11.accdb";
Connection con;
Statement stmt;
String query = "Select * from user";
try {
// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
con = DriverManager.getConnection(url, "", "");
stmt = con.createStatement();
// Returns a ResultSet that contains the data produced by the query;
// never null
ResultSet rs = stmt.executeQuery(query);
System.out.println("User Data:");
System.out.println("FirstName\tLastName\tAge");
while (rs.next()) {
String fName = rs.getString("FirstName");
String lName = rs.getString("LastName");
int age = rs.getInt("age");
System.out.println(fName + "\t" + lName + "\t" + age);
}
stmt.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
As you can see, jackcess 2.1.2 depends on commons-lang 2.6. The version you use (3.4) is not backward compatible.
Why do you have a JDBC driver for MySQL and for HSQLDB if your goal is to connect to MS Access?

MYSQL - Communications link failure; timeout

The class below creates a connection to my MYSQL user, it then submits some data into a table.. I've checked and double checked the username and password, it's definitely 100% correct, but why does it keep throwing this memory leak? I am having trouble figuring this out myself, I've been reading all the related topics, but none really seems to be the same issue as mine.
package com.rs.MYSQL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import com.rs.Settings;
import com.rs.utils.Lottery;
public class LotteryMYSQL {
private static Connection connection;
private static long lastConnection = System.currentTimeMillis();
public static void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://runerebellion.com:3306/database",
"user", "pass");//fake user&pass
} catch (Exception e) {
e.printStackTrace();
}
}
public static void destroyConnection() {
try {
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void init() {
createConnection();
}
public static boolean updateInfo() {
try {
if (Settings.DisableMYSQL == true)
return false;
createConnection();
Statement stmt = connection.createStatement();
if (Lottery.getCurrentLotteryWinner() != null)
stmt.executeUpdate("UPDATE info SET moneyEarned = '"
+ Lottery.options.size() + "', lastWinner = '"
+ Lottery.getCurrentLotteryWinner() + "'");
else
stmt.executeUpdate("UPDATE info SET moneyEarned = '"
+ Lottery.options.size() + "', lastWinner = '"
+ Lottery.getLastLotteryWinner() + "'");
destroyConnection();
} catch (Throwable e) {
if (System.currentTimeMillis() - lastConnection > 10000) {
destroyConnection();
createConnection();
lastConnection = System.currentTimeMillis();
}
}
return false;
}
}
The memory leak is below
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:408)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1137)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:356)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2504)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2541)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2323)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
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:408)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.rs.MYSQL.LotteryMYSQL.createConnection(LotteryMYSQL.java:19)
at com.rs.Launcher.main(Launcher.java:103)
Caused by: java.net.ConnectException: Connection timed out: 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 java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:258)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:306)
... 16 more
Used this:
and it worked fine
Class.forName("com.mysql.jdbc.Driver").newInstance();
String IP = "";
String DB = "";
String User = "";
String Pass = "";
connection = DriverManager.getConnection("jdbc:mysql://" + IP + "/"
+ DB, User, Pass);

“java.lang.ClassNotFoundException” when executing Java code when running in terminal [duplicate]

I was trying to make connection with Oracle 11g via java and i have added ojdbc14 and ojdbc6 but still i am getting this error while compiling.Please help.
java.lang.ClassNotFoundException: com.oracle.jdbc.Driver
Goodbye!
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
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 JDBC.main(JDBC.java:21)
And My Code is
import java.sql.*;
public class JDBC {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Open a connection
try{
Class.forName("com.oracle.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection
("jdbc:oracle:thin:#172.16.209.169:1521:heritage", "USERNAME", "PASSWORD");
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
Handle errors for Class.forName
e.printStackTrace();
}finally{
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
You need to add JDBC driver to your class path.
java.lang.ClassNotFoundException: com.oracle.jdbc.Driver // this error shows that your application is missing oracle jdbc driver.
Download Oracle jdbc driver, then add it to your class path.
Your ojdbc$version.jar seems not to be in the classpath.

JDBC Connection timed out

Trying to create a JDBC based app that connects to a database allowing a user to edit a website.
Each time I test the app from eclipse I get a connection timed out error and have no idea why.
Sorry if it's a n00by question I'm new to JDBC. Any help or suggestions will be greatly appreciated.
Below is my code:
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(
"jdbc:mysql://nkuwebdata.db.8750359.hostedresource.com",
username,
password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * FROM tbl_adminLogin");
while(rs.next())
{
String s = rs.getString("name");
System.out.println(s);
break;
}
} catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Below is the Error Message that is printing out in my console:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException
MESSAGE: Connection timed out: connect
STACKTRACE:
java.net.ConnectException: Connection timed out: 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 java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at com.mysql.jdbc.Connection.<init>(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 uk.co.majorwebdesigns.ContentManager.connectToAndQueryDatabase(ContentManager.java:100)
at uk.co.majorwebdesigns.ContentManager.createMenuBar(ContentManager.java:92)
at uk.co.majorwebdesigns.ContentManager.launch(ContentManager.java:61)
at uk.co.majorwebdesigns.ContentManager.main(ContentManager.java:133)
** END NESTED EXCEPTION **
Last packet sent to the server was 2 ms ago.
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2847)
at com.mysql.jdbc.Connection.<init>(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 uk.co.majorwebdesigns.ContentManager.connectToAndQueryDatabase(ContentManager.java:100)
at uk.co.majorwebdesigns.ContentManager.createMenuBar(ContentManager.java:92)
at uk.co.majorwebdesigns.ContentManager.launch(ContentManager.java:61)
at uk.co.majorwebdesigns.ContentManager.main(ContentManager.java:133)
Connection timeout generally occurs when the database server is not running.
dbname is missing in your code i guess. Just check this link
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
conn.close();
Several things: database not locally via localhost:3306 but over the net must pass through the firewall.
A port might be in order, for MySQL the default is 3306, as in localhost:3306.
Both these things might mean no connection, and would explain your error.
Things should be closed; otherwise one might run out of connections and such.
This can best be done with the try-with-resources construct.
And then one should almost use PreparedStatements to escape backslashes and quotes, and prevent SQL injection.
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
try (Connection con = DriverManager.getConnection(
"jdbc:mysql://nkuwebdata.db.8750359.hostedresource.com",
username,
password)) {
String sql = "SELECT * FROM tbl_adminLogin";
try (PreparedStatement stmt = con.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
String s = rs.getString("name");
System.out.println(s);
}
}
}
}
}
Check your connections credentials then also check server you are connecting is up and running.

Categories