I am connecting to a db2 database server using this piece of java code.
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DatabaseConnect {
Connection co=null;
Statement st=null;
PreparedStatement pstmt;
ResultSet rs;
int status;
void makeConnection() throws ClassNotFoundException, SQLException
{
Class.forName("com.ibm.db2.jcc.DB2Driver");
co=DriverManager.getConnection("jdbc:db2://localhost:50000/databasename","username","password");
//st=co.createStatement();
}
Connection getConnection()
{
return co;
}
void endConnection() throws SQLException
{
co.close();
}
public static void main(String args[]) throws ClassNotFoundException, SQLException
{
DatabaseConnect db=new DatabaseConnect();
db.makeConnection();
new MaintainHash().createHashMap(db.getConnection());
new Login(db.getConnection()).setVisible(true);
}
}
It works good if hostname is localhost but when i provide hostname of remote server, the program hangs and shows this error.
Exception in thread "main" com.ibm.db2.jcc.am.DisconnectNonTransientConnectionException: [jcc][t4][2043][11550][3.68.61] Exception java.net.ConnectException: Error opening socket to server /192.168.80.1 on port 50,000 with message: Connection timed out: connect. ERRORCODE=-4499, SQLSTATE=08001
at com.ibm.db2.jcc.am.gd.a(gd.java:329)
at com.ibm.db2.jcc.am.gd.a(gd.java:410)
at com.ibm.db2.jcc.t4.ac.a(ac.java:439)
at com.ibm.db2.jcc.t4.ac.<init>(ac.java:96)
at com.ibm.db2.jcc.t4.a.b(a.java:358)
at com.ibm.db2.jcc.t4.b.newAgent_(b.java:2066)
at com.ibm.db2.jcc.am.Connection.initConnection(Connection.java:780)
at com.ibm.db2.jcc.am.Connection.<init>(Connection.java:725)
at com.ibm.db2.jcc.t4.b.<init>(b.java:333)
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:474)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:115)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at DatabaseConnect.makeConnection(DatabaseConnect.java:31)
at DatabaseConnect.main(DatabaseConnect.java:58)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.ibm.db2.jcc.t4.w.run(w.java:49)
at java.security.AccessController.doPrivileged(Native Method)
at com.ibm.db2.jcc.t4.ac.a(ac.java:425)
... 14 more
Java Result: 1
BUILD SUCCESSFUL (total time: 25 seconds)
I am able to telnet and ping to the host ip address.
Got it.
The solution is actually quite simple as well as a bit off topic. Thanks Ian for pointing it out. I had to add port number of db2 to the inbound and outbound rules of firewall.
If anyone is having the same problem, you can follow these steps:
Go to Windows Firewall in control panel.
Click on Advanced Settings.
Select Inbound Rules and then click on New Rule.
Select Port option and then type the port number you want to add.
Repeat the above steps for outbound rules.
Related
This question already has answers here:
java.net.ConnectException: Connection refused
(19 answers)
Closed 1 year ago.
I'm using Eclipse to connect to a remote database with the following details:
name: MSbdd**
Hostname 155.158.xxx.xx
Port: 1521
SID: olt*****
And the authentication type: Default
username: msbd**
password: haslo****
This is the code I have in Eclipse:
package net.codejava;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JavaOracleTest {
public static void main(String[] args) {
String dbURL = "jdbc:oracle:thin:#localhost:1521:xe";
String username = "msbd**";
String password = "haslo****";
try {
Connection connection = DriverManager.getConnection(dbURL, username, password);
System.out.println("Połączono z serwerem Oracle");
} catch (SQLException e) {
System.out.println("Error");
e.printStackTrace();
}
}
}
And this is the error I get:
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection (CONNECTION_ID=yV+3U5v4TK2js7gMFTixxA==)
Error
at oracle.jdbc.driver.T4CConnection.handleLogonNetException(T4CConnection.java:882)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:687)
at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:1086)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:90)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:728)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:649)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at net.codejava.JavaOracleTest.main(JavaOracleTest.java:15)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection (CONNECTION_ID=yV+3U5v4TK2js7gMFTixxA==)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:677)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:568)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:953)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:350)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:2155)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:652)
... 7 more
Caused by: java.io.IOException: Connection refused: connect, socket connect lapse 2003 ms. localhost 1521 0 (2/2) true
at oracle.net.nt.TcpNTAdapter.establishSocket(TcpNTAdapter.java:421)
at oracle.net.nt.TcpNTAdapter.doLocalDNSLookupConnect(TcpNTAdapter.java:303)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:265)
at oracle.net.nt.ConnOption.connect(ConnOption.java:238)
at oracle.net.nt.ConnStrategy.executeConnOption(ConnStrategy.java:902)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:638)
... 12 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:482)
at java.base/sun.nio.ch.Net.connect(Net.java:474)
at java.base/sun.nio.ch.SocketChannelImpl.connect(SocketChannelImpl.java:694)
at java.base/java.nio.channels.SocketChannel.open(SocketChannel.java:194)
at oracle.net.nt.TimeoutSocketChannel.connect(TimeoutSocketChannel.java:184)
at oracle.net.nt.TimeoutSocketChannel.<init>(TimeoutSocketChannel.java:158)
at oracle.net.nt.TcpNTAdapter.establishSocket(TcpNTAdapter.java:380)
... 17 more
I've replaced some details with * because it's a database from school.
Your error is:
Caused by: java.net.ConnectException: Connection refused: connect
Check that you have:
The correct hostname.
For example, you say that the hostname is 155.158.xxx.xx but you are using:
String dbURL = "jdbc:oracle:thin:#localhost:1521:xe";
Should it be:
String dbURL = "jdbc:oracle:thin:#155.158.xxx.xx:1521:xe";
the correct port.
the correct SID.
For example, should it be:
String dbURL = "jdbc:oracle:thin:#155.158.xxx.xx:1521:olt*****";
the correct username and password.
access to the database.
I.e. you are running it on a network that can access the server and not from a network that cannot access the server (your school may require you to be directly connected to or logged in to their network to access the server and may refuse connections from unauthenticated users outside their network).
How can I check the possible reason for java.net.SocketTimeoutException.
I have a program that just pings to a website. however I am getting SocketTimeoutException. I know it is happening due to timeout expiring before the connection is established. But I want to know the precise reason of the issue. Like It is to do with internal DNS failure or due to unavailability of the internet or what !
Tried searching for similar questions but I didn't get the exact reason for not being able to establish the connection.
Below code snippet explains the problem
import java.net.HttpURLConnection;
import java.net.URL;
public class URLConnectionTest {
public static void main(String[] args) {
try {
String urlString = "https://www.google.com";
URL url = new URL (urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.connect();
System.out.println("Connected !!!");
}
catch(Exception e) {
System.out.println("Error occurred while connecting" + e);
}
}
}
Now there are multiple outputs for different case.
When I turned off laptop's wifi
Error occurred while connecting java.net.UnknownHostException: www.google.com
When I connect to wifi but router doesn't have the connectivity
Error occurred while connecting java.net.SocketTimeoutException: connect timed out
Few lines of Stacktrace for Timeout
java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
I have a MySQL database. My friend is trying to access it from a different computer using my public IP.
This is the program he used to test the connection:
public class Main {
public static void main(String args[]) {
String url = "jdbc:mysql://IPadresss:3307/javabase";
String username = "bob";
String password = "bob";
Properties properties = new Properties();
properties.setProperty("bob", "bob");
properties.setProperty("bob", "bob");
properties.setProperty("useSSL", "false");
properties.setProperty("autoReconnect", "true");
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, properties)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
}
This is the error my friend, who is the client, gets:
Connecting database...
Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
at SQLConnector.Main.main(Main.java:23)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
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:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2163)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2088)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
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:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
at SQLConnector.Main.main(Main.java:20)
Caused by: java.sql.SQLException: Access denied for user ''#'Freinds ip' (using password: NO)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:873)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1710)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1226)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
at com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2104)
... 13 more
Please help me find out what is wrong with my method of connecting to the server, I have remotely given privileges to my friend (user "bob").
So, you have the following error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure java.net.ConnectException: Connection
refused
This could happen for a variety of reasons, and I'm quoting from this answer
If you get a SQLException: Connection refused or Connection timed out
or a MySQL specific CommunicationsException: Communications link
failure, then it means that the DB isn't reachable at all.
This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL. [Assuming the one you mentioned is correct]
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advice:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure
firewall/proxy to allow/forward the port.
In my RMI program I want to set up my RMI registry on the port 8080, but when I do it, I get an exception.
Here is my server code
public class Server {
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(8080);
MathServerImpl mathServer = new MathServerImpl();
Naming.rebind("MathServer", mathServer);
System.out.println("Math Server has started and is running");
} catch (RemoteException | MalformedURLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
The code works properly for the port 1099, which is it's default port as far as I know, but for this case it gives me a java.net.ConnectException, and here is the log.
java.rmi.ConnectException: Connection refused to host: 10.100.25.173; nested exception is:
java.net.ConnectException: Connection refused
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:341)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at java.rmi.Naming.rebind(Naming.java:177)
at server.Server.main(Server.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
... 11 more
You are creating a registry on port 8080 but then attempting to rebind your object in the default registry on port 1099. You need to either:
pass a full URL to Naming.rebind including the port number, i.e. //localhost:8080/MathServer or
save a reference to the Registry object returned by LocateRegistry.createRegistry and bind the object using that registry's instance methods rather than the static methods of Naming
Similarly, you will need to use the full //localhost:8080/MathServer URL form in your clients when they lookup the object, to make sure they're talking to the right registry.
Naming.rebind("MathServer", mathServer);
Change that to
Naming.rebind("//localhost:8080/MathServer", mathServer);
If you are linux Ubuntu user then while starting RMI registry use command
rmiregistry 8080 &
For Windows
start rmiregistry 8080
Following is the code.
import java.sql.*;
public class ActivityReader {
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have already added mysql-connector-java-5.1.20-bin.jar in project from this url.
Mysql service is already running.
mysql start/running, process 25326
MySQL Connect Example.
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(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:348)
at c
om.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2391)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2428)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2213)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:797)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at ActivityReader.main(ActivityReader.java:45)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:218)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:257)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
... 15 more
Any idea.... ??????
Connect using 127.0.0.1 instead localhost, maybe a clue of what is happening on your system:
MySQL will try to connect to the unix socket if you tell it to connect
to "localhost". If you tell it to connect to 127.0.0.1 you are forcing
it to connect to the network socket. So probably you have MySQL
configured to only listen to the network socket and not to the file
system socket.
https://serverfault.com/questions/295285/mysql-cannot-connect-via-localhost-only-127-0-0-1
try
>telnet localhost 3306
You are supposed to see some server response similar to
"5.5.19☺(:*b2p`p!☻ǧ4Oph7xxsV5C5mysql_native_password"
Most probably problem will be fixed by replacing hostname with ip, check https://serverfault.com/a/90055
I think you are not specified your db name in your connection URL try this conn = DriverManager.getConnection(url +"/"+ dbName ,userName,password); And be sure that you have created the database with same name.
I face the same issue on a VPS linux server. I solve it by replacing localhost or 127.0.0.1 by the real IP address.
If you are trying to run your code on a Linux Machine or Windows Server.
You can change the server from 'localhost' to specific IP 'xx.xx.xx.xx'
and it should work fine.