This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 5 years ago.
I try to connect with my DB (MySQL) from a servlet but I get Connection refused error. I read similar questions like this. However:
You have not started your server.
In my local server (Ubuntu server 16.04), with IP 192.168.0.4 is installed MySQL server. MySQL Server is running as the command service mysql status give this output:
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2017-03-21 11:50:56 EET; 1 weeks 1 days ago
Main PID: 1209 (mysqld)
You are trying to connect to the wrong IP/port.
MySQL is listening to port 3306, as the command netstat -an | grep 3306.
gives the following output
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
A firewall is blocking your connection before it reaches your server.
The server's firewall is disabled, as ufw status
Status: inactive
I disabled my PC's firewall too but it didn't solve the connection error.
Your server has too many pending connections waiting to be accepted.
My server is fresh installed and there is no way to have any pending connections.
Your server is not listening for connections.
I run the commnand nmap -sT -O localhost and I got:
Not shown: 993 closed ports
PORT STATE SERVICE
21/tcp open ftp
22/tcp open ssh
25/tcp open smtp
80/tcp open http
110/tcp open pop3
143/tcp open imap
3306/tcp open mysql
NETBEANS
Me and Server we are in the same network. My Java class which handles the communication with the DB contains:
private final String WEBAPP_DB = "jdbc:mysql://192.168.0.4:3306/myDataBase";
private final String JDBC_DRIVER="com.mysql.jdbc.Driver";
private final String USERNAME = "myUserName";
private final String PASSWORD = "myPassWord";
Connection c = null;
PreparedStatement stm = null;
sq = "SELECT * FROM Machines";
try {
Class.forName(JDBC_DRIVER);
c = DriverManager.getConnection(WEBAPP_DB, USERNAME, PASSWORD);
stm = c.prepareStatement(sq);
ResultSet rs = stm.executeQuery();
while(rs.next()){
System.out.println("Machine = " + rs.getInt("id"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stm != null) {
stm.close();
}
if (c != null) {
c.close();
}
}
and some of the errors I get is
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.
...
Caused by: java.net.ConnectException: Connection refused: connect
Any hint what may be the problem?
If you're trying to connect yo your MySql server remotely, the problem is in the MySql server network configuration, it's listening on localhost (127.0.0.1):
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
It should be:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
Or at least, instead of 0.0.0.0, your server ip address (192.168.0.4).
I suggest to read this How to Bind to Static IP address in MySQL
On the other hand, if you're connecting locally (your code is executed on MySql server, which is the same machine where NetBeans runs) you should change your connection string into jdbc:mysql://localhost:3306/myDataBase
P.S. So at resuming your questionnaire :)
You are trying to connect to the wrong IP.
Related
This question already has answers here:
java.net.ConnectException: Connection refused
(19 answers)
Closed 3 years ago.
So today I decided my website would run faster if I moved our databases to a different server, so I did, you can see how I am connecting below:
final String driver = "com.mysql.jdbc.Driver";
final String url = "jdbc:mysql://external_ip_address_here:3306/dbname";
final String username = "user";
final String password = "pass";
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
This works fine when I am connecting to 127.0.0.1 / localhost, now I am getting this error:
java.net.ConnectException
MESSAGE: Connection refused (Connection refused)
My MySQL server is running Ubuntu 18.04.
I added multiple firewall rules to try and allow all incoming connections to port 3306 - sudo ufw allow from any to any port 3306 proto tcp & I tried iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT, still not working, when i port scan the network it shows port 3306 as closed
FIX 1: This fixed the connection refused error -
Step 1: edit file /etc/mysql/mysql.conf.d/mysqld.cnf
Step 2: remove line bind-address = 127.0.0.1
Check the servers firewall configurations. It may be the reason for your problem. Add a new rule that allows connection from your URL in firewall settings.
This fixed the connection refused error -
Step 1: edit file /etc/mysql/mysql.conf.d/mysqld.cnf
Step 2: remove line bind-address = 127.0.0.1
I'm trying to access a Azure-hosted SQL database on my java application. I checked the port 1433 using nmap and it shows that it's closed:
Starting Nmap 7.12 ( https://nmap.org ) at 2016-09-02 09:44 PHT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00014s latency).
Other addresses for localhost (not scanned): ::1
PORT STATE SERVICE
1433/tcp closed ms-sql-s
I have edited the /etc/pf.conf and restarted my mac but the port is still closed. Here is my pf.conf:
scrub-anchor "com.apple/*"
nat-anchor "com.apple/*"
rdr-anchor "com.apple/*"
dummynet-anchor "com.apple/*"
anchor "com.apple/*"
load anchor "com.apple" from "/etc/pf.anchors/com.apple"
pass in proto tcp from any to any port 1433
Also, my firewall is set to off.
My java app is throwing this error:
Error starting database: The TCP/IP connection to the host flowengine7.database.windows.net, port 1433 has failed. Error: "Connection timed out: no further information. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
Java code:
String connectionString =
"jdbc:sqlserver://dbName.database.windows.net:1433;database=dbName;user=user##user;password=passwordhere;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;";
Connection connection = null;
try {
connection = DriverManager.getConnection(connectionString);
println 'connected';
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (connection != null) try {
connection.close();
} catch (Exception e) {
}
}
You're overlooking the Azure SQL server-level Firewall:
https://azure.microsoft.com/en-us/documentation/articles/sql-database-configure-firewall-settings/
You need to whilelist your Mac's Public IP address in there to be able to connect from local. By default only Azure services can reach 1433/TCP on your Azure SQL instance (permitted by Allow access to Azure Services setting in the Azure SQL Firewall).
If you're getting a new Public IP address every time you reboot your DSL/Cable/Fiber modem you'll need to define a whole range of addresses not just the one (i.e. 174.73.0.0 - 174.73.255.255 vs. listing 174.73.16.180). Hopefully you'll always grab an IP address in the same range.
How can I connect to internet server from Java desktop application? I need to access MySQL database and upload/download files. The host that I have (one.com), don't support remote database access, so I've tried with SSH. I don't know anything at all about this. I've tried various codes examples but none of them pass further than connection. I add jsch.jar to my project. Is there something else that I have to add/install or what em I missing?
public static void main(String args[])
{
String user = "user";
String password = "pass";
String host = "00.000.00.000";
int port=22;
String remoteFile="/home/mywebsite.com/test.txt";
try
{
JSch jsch = new JSch();
Session session = (Session) jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
System.out.println("Connection established.");
System.out.println("Creating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
System.out.println("SFTP Channel created.");
InputStream out= null;
out= sftpChannel.get(remoteFile);
try (BufferedReader br = new BufferedReader(new InputStreamReader(out))) {
String line;
while ((line = br.readLine()) != null)
System.out.println(line);
}
}
catch(JSchException | SftpException | IOException e){System.err.print(e);}
}
I get the error:
com.jcraft.jsch.JSchException: java.net.ConnectException: Connection timed out: connect
BUILD SUCCESSFUL (total time: 24 seconds)
Or what other alternatives I have to achieve a remote connection to my site & database?
P.S. I have tried almost all the example-codes from stackoverflow and all get stuck in the same point ...
Thank you!
Connection timed out indicates that you're trying to connect to a server that isn't accepting SSH connections on port 22, or your host is incorrect. Is host = "00.000.00.000"; the actual IP address you're trying to connect to, or did you change it for your Stack Overflow question?
I'm not going to debug your code, but will tell you how to accomplish this.
The solution is to use SSH "port forwarding", which you should first set up from the command line, to learn how it works, before embedding it in your Java code. You may not need to write any code if a command-line tunnel will suffice.
ssh -L3306:localhost:3306 <databaseHost>
This creates an SSH "tunnel" from your computer's port 3306 to the <databaseHost> and then on to localhost from <databaseHost>. Any connection on your computer to your local port 3306 gets tunnelled across SSH to <databaseHost> and then on to whatever <databaseHost> knows as localHost, i.e. back to itself, on port 3306.
When your Java code connects to the database, it should connect to localhost:3306. Note that the localhost in your database connect string refers to your computer, while the one in the ssh command is from the point of view of the remote server, so they mean different things.
In summary, a packet from your Java code to the remote MySQL server travels the following route:
Connect to my computer port 3306
Intercepted by ssh
Encrypted and transmitted to remote database server
Decrypted by sshd and fed to port 3306 on the same server
Received by MySQL running on the remote host
For return packets, this process is reversed, managed by the local ssh client and the remote sshd daemon.
Note that this can be used for more interesting cases. For example, suppose the remote ssh server and database server are on different systems behind the same firewall. Let's say the ssh host is visible as gateway.xyz.com, while the database host is on an internal LAN at 10.0.0.3 which is not reachable from the Internet, but reachable from the gateway.
ssh -L3306:10.0.0.3:3306 gateway.xyz.com
The packet route is then
Your computer 3306
Received by ssh
Encryption and sent to gateway.xyz.com
Decrypted by sshd forwarded to 10.0.0.3:3306
Received at 10.0.0.3:3306 by MySQL
To be clear, this is something you set up from the command line, before executing your Java code, which should happen in a different session from the ssh command. The tunnel remains available as long as the ssh command is running.
This question already has answers here:
JDBC connection failed, error: TCP/IP connection to host failed
(9 answers)
Closed 5 years ago.
I want to connect Java class file with SQL server 2008. I have logged in with SQL server authentication use: sa, pass:123456. But i am receiving error in connectivity.
static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
static String dburl = "jdbc:sqlserver://localhost\\SQL2008:1433;Database=Java";
static String user = "sa";
static String password = "123456";
public static void update() throws Exception{
String sql = "UPDATE Categories SET Id='COM' WHERE Id='LAP'";
Class.forName(driver);
Connection conn = DriverManager.getConnection(dburl, user, password);
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
conn.close();
}
public static void main(String[] args) throws Exception {
Basic.update();
}
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1048)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:829)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:712)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Tutorials.jdbc.Basic.update(Basic.java:48)
at Tutorials.jdbc.Basic.main(Basic.java:72)
Probably a little late to answer this question, but doing it for my own benefit.
The actual TCP port to connect to through JDBC can be found in the registry at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\<Instance Name>\MSSQLServer\SuperSocketNetLib\Tcp
Use this value to connect to SQL Server.
For example
"jdbc:sqlserver://localhost\SQLEXPRESS:49922;databaseName=db;user=user;password=secret"
Also ensure that TCP connections are enabled in the server configuration tools.
I think that your dburl may be malformed.
Try this url instead.
String dburl= "jdbc:sqlserver://localhost\\SQL2008:1433;" +
"databaseName=Java;user=sa;password=123456";
Make sure you have Driver jar file and change your dburl to this as mentioned below
try this
String dburl ="jdbc:sqlserver://SQL2008:1433;DatabaseName=Java;user=sa;Password=123456";
Thanks you for your help, i'm fix my problem, it's not error on String dburl= "jdbc:sqlserver://localhost\SQL2008:1433;Database:Java"
it's error port 1433 no connect in SQL server 2008
Where i find the Protocol TCP/IP, if disabled then Enable it Click on TCP/IP, i'm find its properties.
In this properties Remove All the TCP Dynamic Ports and Add value of 1433 to all TCP Port and restart your SQL Server Services > SQL Server
And Its Done...
Thanks all for your help!
TCP/IP Connection Refused.
Run NETSTAT -A to see a list of ports that are open (they'll say LISTENING) If 1433 isn't among them, then SQL server isn't running or isn't listening on that port. Follow Michael Todd's advice from there.
If 1433 is on the list, check your local firewall to see if it allows connections to/from localhost and/or allows connections to 1433.
You can try TELNET 1433 and see if it connects (you should get a blank screen with a cursor blinking at the top left.) (You may have to enable the telnet client in Programs and Features.) If so then you have a problem with your code.
i am using below code
try {
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb","root","root"); // cust is the DSN Name
} catch (Exception e) {
System.out.println("Exception "+e);
}
got this exception during run time...
tried netstat -a in command prompt to check if mysql is running on port 3306 below is the trace...
Proto Local Address Foreign Address State
TCP user:epmap user:0 LISTENING
TCP user:microsoft-ds user:0 LISTENING
TCP user:3306 user:0 LISTENING
Well, googling your problem i have come to this solution:
Try reseting your user password executing the next statement at your mysql command line client:
SET PASSWORD FOR 'root'#'localhost' = OLD_PASSWORD('root');
As it seems it kind of changes the authentication method at the mysql server.
Let me know if this have worked.
Other option is to check the compatibility between the version of your MySQL database and the MySQL JDBC driver you are using.