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).
Related
i asked this question before but got no answers, i think mainly because it was a mess, i'll state the facts and put some quotes from the code under
im using VMWare, and have one Windows Server 2003 with SQL Server 2005 on it, with a SQL Login, and it has a DNS Service running
i also have a windows 7 machine running NetBeans8.2 with JDK 8.1, using JDBC 4.2
i can connect to the server using SQL Manager from the Windows 7 machine
i can't connect using the java code because of an SSL Error, i am not sure what is causing it
this is for a school project so i must use SQL server 2005
here's my connection code :
package connectbd;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
public class ConnectBD {
public static void main(String[] args) {
String jdbcurl;
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
jdbcurl = "jdbc:sqlserver://SQLSERVER;instanceName=SQLE;user=****;password=****;database=LP_SIBD_GR15";
try {
con=DriverManager.getConnection(jdbcurl);
System.out.println("Connection success");
} catch(SQLException e) {
e.printStackTrace();
}
}
}
This is the error that i get :
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to the SQL Server using Secure Sockets Layer (SSL) encryption. Error: "The SQL Server server returned no response. The connection has been closed. ClientConnectionId:e9655c34-7c66-42c8-aaec-36601b53ff98 ».
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:2826)
****at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1829)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2391)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2042)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1889)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1120)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:700)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at connectbd.ConnectBD.main(ConnectBD.java:35)
Caused by: java.io.IOException:
The SQL Server server returned no response. The connection was closed. ClientConnectionId:e9655c34-7c66-42c8-aaec-36601b53ff98
****at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.ensureSSLPayload(IOBuffer.java:786)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.readInternal(IOBuffer.java:836)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.read(IOBuffer.java:829)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.readInternal(IOBuffer.java:999)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.read(IOBuffer.java:989)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:983)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1385)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1397)
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1756)
... 8 more
BUILD SUCCESSFUL (total time: 1 second)
i believe the causes are somewhere in these 2 lines: the ones marked by **** at the start
i have to deliver a webservices project for school in 2 weeks, and this is kind of a huge obstacle, any quick help or suggestion would be very appreciated
You will need to add few parameters to specify the ssl connection, such as integratedSecurity=true, encrypt=true and trustServerCertificate=true.
jdbcurl = "jdbc:sqlserver://SQLSERVER;instanceName=SQLE;user=****;password=****;database=LP_SIBD_GR15;integratedSecurity=true;encrypt=true;trustServerCertificate=true";
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.
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.
I am trying to connect to MBean server. I need to write JMX Client application. This is the code used for client application. But I have got an exception related to this
Failed to retrieve RMIServer stub:
javax.naming.ServiceUnavailableException [Root exception is
java.rmi.ConnectException: Connection refused to host: localhost;
nested exception is:
Can somebody help me to fix this.
import java.io.IOException;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
public class SystemConfigClient {
public static final String HOST = "localhost";
public static final String PORT = "1099";
public static void main(String[] args) throws IOException, MalformedObjectNameException {
JMXServiceURL url =new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" +PORT+ "/jmxrmi");
JMXConnector jmxConnector = JMXConnectorFactory.connect(url);
MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
//ObjectName should be same as your MBean name
ObjectName mbeanName = new ObjectName("ifs.demo1.jmx:type=SystemConfig");
//Get MBean proxy instance that will be used to make calls to registered MBean
SystemConfigMBean mbeanProxy =
(SystemConfigMBean) MBeanServerInvocationHandler.newProxyInstance(
mbeanServerConnection, mbeanName, SystemConfigMBean.class, true);
//let's make some calls to mbean through proxy and see the results.
System.out.println("Current SystemConfig::" + mbeanProxy.doConfig());
mbeanProxy.setSchemaName("NewSchema");
mbeanProxy.setThreadCount(5);
System.out.println("New SystemConfig::" + mbeanProxy.doConfig());
//let's terminate the mbean by making thread count as 0
mbeanProxy.setThreadCount(0);
//close the connection
jmxConnector.close();
}
}
I have run this code with following arguments.
Dcom.sun.management.jmxremote Dcom.sun.management.jmxremote.port=1099
Dcom.sun.management.jmxremote.authenticate=false
Dcom.sun.management.jmxremote.ssl=false
but I got the exception of
Exception in thread "main" java.io.IOException: Failed to retrieve
RMIServer stub: javax.naming.ServiceUnavailableException [Root
exception is java.rmi.ConnectException: Connection refused to host:
localhost; nested exception is: java.net.ConnectException:
Connection refused: connect] at
javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:338)
at
javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:248)
at
javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:207)
at com.demo1.jmx.SystemConfigClient.main(SystemConfigClient.java:29)
Caused by: javax.naming.ServiceUnavailableException [Root exception is
java.rmi.ConnectException: Connection refused to host: localhost;
nested exception is: java.net.ConnectException: Connection refused:
connect] at
com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:101)
at
com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:185)
at javax.naming.InitialContext.lookup(InitialContext.java:392) at
javax.management.remote.rmi.RMIConnector.findRMIServerJNDI(RMIConnector.java:1886)
at
javax.management.remote.rmi.RMIConnector.findRMIServer(RMIConnector.java:1856)
at
javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:257)
... 3 more Caused by: java.rmi.ConnectException: Connection refused
to host: localhost; nested exception is: java.net.ConnectException:
Connection refused: connect at
sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:601) at
sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:198)
at
sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:184)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:322) at
sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source) at
com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:97)
... 8 more Caused by: java.net.ConnectException: Connection refused:
connect at java.net.PlainSocketImpl.socketConnect(Native Method) at
java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333) at
java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182) 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.(Socket.java:375) at
java.net.Socket.(Socket.java:189) at
sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:22)
at
sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:128)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:595)
... 13 more Java Result: 1
Have you noticed that you are using the VM arguments with "D" and not "-D"? Or is it just a typo?
The correct would be:
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=1099
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
my sql server instance name is MYPC\SQLEXPRESS and I'm trying to create a jTDS connection string to connect to the database 'Blog'. Can anyone please help me accomplish that?
I'm trying to do like this:
DriverManager.getConnection("jdbc:jtds:sqlserver://127.0.0.1:1433/Blog", "user", "password");
and I get this:
java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:395)
at net.sourceforge.jtds.jdbc.ConnectionJDBC3.<init>(ConnectionJDBC3.java:50)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at SqlConnection.Connect(SqlConnection.java:19)
at main.main(main.java:11)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3(SharedSocket.java:305)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:255)
at net.sourceforge.jtds.jdbc.ConnectionJDBC2.<init>(ConnectionJDBC2.java:323)
... 6 more
As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC, you may end up with something like this:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t
Or, if you prefer to use getConnection(url, "sa", "s3cr3t"):
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
EDIT: Regarding your Connection refused error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.
Really, really, really check if the TCP/IP protocol is enabled in your local SQLEXPRESS instance.
Follow these steps to make sure:
Open "Sql Server Configuration Manager" in "Start Menu\Programs\Microsoft SQL Server 2012\Configuration Tools\"
Expand "SQL Server Network Configuration"
Go in "Protocols for SQLEXPRESS"
Enable TCP/IP
If you have any problem, check this blog post for details, as it contains screenshots and much more info.
Also check if the "SQL Server Browser" windows service is activated and running:
Go to Control Panel -> Administrative Tools -> Services
Open "SQL Server Browser" service and enable it (make it manual or automatic, depends on your needs)
Start it.
That's it.
After I installed a fresh local SQLExpress, all I had to do was to enable TCP/IP and start the SQL Server Browser service.
Below a code I use to test the SQLEXPRESS local connection. Of course, you should change the IP, DatabaseName and user/password as needed.:
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JtdsSqlExpressInstanceConnect {
public static void main(String[] args) throws SQLException {
Connection conn = null;
ResultSet rs = null;
String url = "jdbc:jtds:sqlserver://127.0.0.1;instance=SQLEXPRESS;DatabaseName=master";
String driver = "net.sourceforge.jtds.jdbc.Driver";
String userName = "user";
String password = "password";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connected to the database!!! Getting table list...");
DatabaseMetaData dbm = conn.getMetaData();
rs = dbm.getTables(null, null, "%", new String[] { "TABLE" });
while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); }
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.close();
rs.close();
}
}
}
And if you use Maven, add this to your pom.xml:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>
jdbc:jtds:sqlserver://x.x.x.x/database replacing x.x.x.x with the IP or hostname of your SQL Server machine.
jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS
or
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
If you are wanting to set the username and password in the connection string too instead of against a connection object separately:
jdbc:jtds:sqlserver://MYPC/Blog;instance=SQLEXPRESS;user=foo;password=bar
(Updated my incorrect information and add reference to the instance syntax)
A shot in the dark, but
From the looks of your error message, it seems that either the sqlserver instance is not running on port 1433 or something is blocking the requests to that port
SQLServer runs the default instance over port 1433. If you specify the port as port 1433, SQLServer will only look for the default instance. The name of the default instance was created at setup and usually is SQLEXPRESSxxx_xx_ENU.
The instance name also matches the folder name created in Program Files -> Microsoft SQL Server. So if you look there and see one folder named SQLEXPRESSxxx_xx_ENU it is the default instance.
Folders named MSSQL12.myInstanceName (for SQLServer 2012) are named instances in SQL Server and are not accessed via port 1433.
So if your program is accessing a default instance in the database, specify port 1433, and you may not need to specify the instance name.
If your program is accessing a named instance (not the default instance) in the database DO NOT specify the port but you must specify the instance name.
I hope this clarifies some of the confusion emanating from the errors above.