I read quite a few articles here about how to connect from java to a mysql database. Somehow, this does not work for me, and I cannot find out what I do wrong. First, here is my code:
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
class sqltest{
private static int uid = -1;
protected static Connection dbConn = null;
public static void main (String args[]){
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet rs = null;
try{
dbConn = DriverManager.getConnection("jdbc:mysql://XXX.XXX.XX.XX:XXXX/peXXXXX","XXXXXX","XXXXXX");
PreparedStatement ps = dbConn.prepareStatement("select id from supervisor where username = philipp");
rs = ps.executeQuery();
uid = rs.getInt("id");
}catch(SQLException e){
e.printStackTrace();
}
System.out.println(uid);
}
}
The connection details (user, password, adress) are correct. There is only one thing I don't understand: There is already a java-web-applet which is establishing such a connection, and it uses no port (is this possible?).
Now these are my errors that I get:
When I use no port or the default 3306 port, i get this error:
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:173)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:268)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2745)
at com.mysql.jdbc.Connection.<init>(Connection.java:1553)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at sqltest.main(sqltest.java:27)
** END NESTED EXCEPTION **
Last packet sent to the server was 28 ms ago.-1
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2820)
at com.mysql.jdbc.Connection.<init>(Connection.java:1553)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at sqltest.main(sqltest.java:27)
I assume that this is caused by a wrong port. Is this right?
When I use the port that i assume is the right one, I get no error, but the program just runs endlessly and will not come to any result.
Thx for any help!
Make sure you're connecting to the right host/port and that these are accessible.
To do this, e.g. open a terminal and type telnet <host> <port> from the same
machine on which you're running the Java code.
I did a quick online port scan for that address and it looks like the server side is not listening on port xxxxx. Maybe firewall configuration? Or just stopped server/wrong address.
Yes,
a wrong port may cause this exception. The statement looks wrong. If you have more that a million records in the table you might wait days.
Running endlessly seems very unusual given there are no loops in your code. My guess is the SQL query is taking a very long time.
Warning: this code is wrong!
PreparedStatement ps = dbConn.prepareStatement("select id from supervisor where username = philipp");
I guess you'd need to test this against MySQL to be sure, but in most databases I have worked with, an unquoted string literal like that will throw an error.
Also, runtime variables in a query ought to use bind variables with a prepared statement.
In regard to the connection failure, I would say that if specifying the correct port number yields a different error than not specifying a port number, then the default port number is not the same as what you are using. That is surprising. I think 3306 is fairly well known as MySQL's default port. I am not familiar with this driver: org.gjt.mm.mysql.Driver. Try the standard MySQL driver first.
Next, since using the right port number connects, but you say it sits there, My guess is select id from supervisor where username = philipp is running long. I am still surprised it compiled given what I said earlier, but you can try running it in MySQL yourself. Bring up the mysql command-line client and run it.
If it runs slow there too, then you know it is not a Java issue. Do some tuning on it. Perhaps the username column is not indexed and you have millions of rows. Check the execution plan to know for sure.
[Edit 1]
A good technique when a program seems "stalled" is to add print statements at various points. I suggest putting a bunch of System.out.println calls to see between which lines of code are we hung? That will help you narrow the problem space.
Ok this question is answered:
The SQL-Database can be contacted from outside my university environment. But it is located on a server which is blocking my communication. Unfortunately, this was not written into the server's log-file.
Thank you guys for your help!
Related
When trying to launch a Java Action within Oozie (CDH6.3.1) I get a GSS initiate failed. The code in question is pretty straight forward:
String impalaUrl = "jdbc:impala://pxyserver.global.ad:21050/default;SSL=1;AuthMech=1;KrbRealm=GLOBAL.AD;KrbHostFQDN=pxyserver.global.ad;KrbServiceName=Impala;sslTrustStore=/opt/cloudera/security/jks/truststore.jks;trustStorePassword=password";
Properties impalaProperties = new Properties();
impalaProperties.put("user", "svcaccount");
impalaProperties.put("password", "svcpassword");
impalaProperties.put("Driver", "com.cloudera.impala.jdbc41.Driver");
try {
setConnection(DriverManager.getConnection(impalaUrl , impalaProperties));
} catch (SQLException e) {
e.printStackTrace();
}
Running this gives the following stack trace:
java.sql.SQLException: [Cloudera][ImpalaJDBCDriver](500164) Error initialized or created transport for authentication: [Cloudera][ImpalaJDBCDriver](500169) Unable to connect to server: GSS initiate failed.
at com.cloudera.impala.hivecommon.api.HiveServer2ClientFactory.createTransport(Unknown Source)
at com.cloudera.impala.hivecommon.api.ServiceDiscoveryFactory.createClient(Unknown Source)
at com.cloudera.impala.hivecommon.core.HiveJDBCCommonConnection.establishConnection(Unknown Source)
at com.cloudera.impala.impala.core.ImpalaJDBCDSIConnection.establishConnection(Unknown Source)
at com.cloudera.impala.jdbc.core.LoginTimeoutConnection.connect(Unknown Source)
at com.cloudera.impala.jdbc.common.BaseConnectionFactory.doConnect(Unknown Source)
at com.cloudera.impala.jdbc.common.AbstractDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
I can fix this by kiniting with a keytab. However in our production environment Oozie runs this on one of many worker nodes and they do not have valid kerberos tickets. What are my options here? If possible I'd rather not kinit every day on each of our 40 worker nodes, is there a parameter I am missing here?
Thanks
I've installed GridDB on Ubuntu. I use 2 computers: first computer is used as GridDB server, second as java Client and when i try to connect to GriDB from second computer it throws Exception, but when I run java code in server side it works completely fine. What's the problem? I use this tutorial.
Here is simple java code:
import java.util.Arrays;
import java.util.Properties;
import com.toshiba.mwcloud.gs.Collection;
import com.toshiba.mwcloud.gs.GSException;
import com.toshiba.mwcloud.gs.GridStore;
import com.toshiba.mwcloud.gs.GridStoreFactory;
import com.toshiba.mwcloud.gs.Query;
import com.toshiba.mwcloud.gs.RowKey;
import com.toshiba.mwcloud.gs.RowSet;
// Operaton on Collection data
public class Sample1 {
static class Person {
#RowKey String name;
boolean status;
long count;
byte[] lob;
}
public static void main(String[] args) throws GSException {
// Get a GridStore instance
Properties props = new Properties();
props.setProperty("notificationAddress", "239.0.0.1");
props.setProperty("notificationPort", "31999");
props.setProperty("clusterName", "defaultCluster");
props.setProperty("user", "admin");
props.setProperty("password", "admin");
GridStore store = GridStoreFactory.getInstance().getGridStore(props);
// Create a Collection (Delete if schema setting is NULL)
Collection<String, Person> col = store.putCollection("col01", Person.class);
}
}
here is Exception, when i try to connect from second computer:
com.toshiba.mwcloud.gs.common.GSConnectionException: [145028:JC_BAD_CONNECTION] Failed to connect (address=/127.0.1.1:10001, reason=Connection refused: connect)
at com.toshiba.mwcloud.gs.subnet.NodeConnection.<init>(NodeConnection.java:142)
at com.toshiba.mwcloud.gs.subnet.NodeConnectionPool.resolve(NodeConnectionPool.java:163)
at com.toshiba.mwcloud.gs.subnet.NodeResolver.updateConnectionAndClusterInfo(NodeResolver.java:644)
at com.toshiba.mwcloud.gs.subnet.NodeResolver.prepareConnectionAndClusterInfo(NodeResolver.java:529)
at com.toshiba.mwcloud.gs.subnet.NodeResolver.getPartitionCount(NodeResolver.java:205)
at com.toshiba.mwcloud.gs.subnet.GridStoreChannel$5.execute(GridStoreChannel.java:2106)
at com.toshiba.mwcloud.gs.subnet.GridStoreChannel.executeStatement(GridStoreChannel.java:1675)
at com.toshiba.mwcloud.gs.subnet.GridStoreChannel.executeResolver(GridStoreChannel.java:1912)
at com.toshiba.mwcloud.gs.subnet.GridStoreChannel.resolvePartitionId(GridStoreChannel.java:2103)
at com.toshiba.mwcloud.gs.subnet.SubnetGridStore.putContainer(SubnetGridStore.java:968)
at com.toshiba.mwcloud.gs.subnet.SubnetGridStore.putCollection(SubnetGridStore.java:1024)
at com.toshiba.mwcloud.gs.subnet.SubnetGridStore.putCollection(SubnetGridStore.java:787)
at com.toshiba.mwcloud.gs.subnet.SubnetGridStore.putCollection(SubnetGridStore.java:98)
at pac.Main.main(Main.java:39)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(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.toshiba.mwcloud.gs.subnet.NodeConnection.<init>(NodeConnection.java:129)
... 13 more
Caused by: java.net.ConnectException: Connection refused: connect
The problem is that the server is not accepting connections from the second machine. This could be due to a number of things. The most likely are:
Your server is not listening for requests on its external IP address. (For example, the DB may be listening on 127.0.0.1 only.) On the server, check what services are listening on the server's external IP address; e.g. https://www.tecmint.com/find-listening-ports-linux/.
Your client may be configured to talk to the wrong server, or to use the wrong port.
Firewalls. (Though the normal firewall behavior would be to drop the connection packets, leading to a different exception.)
There are other possibilities, but the above should be enough to get you started.
If the above haven't identified the problem, you will need to resort to things like:
Check to see what happens when you connect to that database server / port using a TCP diagnostic tool. Does it connect at the TCP level?
Use a network packet sniffer to see what happens to the TCP packets when the client tries to connect to the database.
Check your route tables and IP tables for strange routing rules. If you are using a virtual machine, check at the hypervisor level too.
239.0.0.1 is a multicast address. And often it needs to do some additional steps with OS, router settings to enable multicast.
So it makes sense to check if multicast is enabled: https://serverfault.com/questions/294207/how-can-i-test-multicast-udp-connectivity-between-two-servers
And also you could check that the IP/port, with which the GridDB node is registered in the cluster, is accessible.
The IP address can be obtained with next command:
$ gs_stat -u admin/admin
I'm trying to connect a simple RabbitMQ using java code to my server (which is executing the RabbitMQ service).
Executing the following code (source here) gives me the java.net.SocketException: Connection Reset exception.
import java.io.*;
import java.security.*;
import com.rabbitmq.client.*;
public class test
{
public static void main(String[] args) throws Exception
{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("myIP"); //myIP is just dummy text, I have a real IP there
factory.setPort(5672);
factory.setUsername("admin");
factory.setPassword("sesgo");
factory.setVirtualHost("vSESGO");
factory.useSslProtocol();
Connection conn = factory.newConnection();
Channel channel = conn.createChannel();
channel.queueDeclare("rabbitmq-java-test", false, true, true, null);
channel.basicPublish("", "rabbitmq-java-test", null, "Hello, World".getBytes());
GetResponse chResponse = channel.basicGet("rabbitmq-java-test", false);
if(chResponse == null) {
System.out.println("No message retrieved");
} else {
byte[] body = chResponse.getBody();
System.out.println("Recieved: " + new String(body));
}
channel.close();
conn.close();
}
}
I've looked for an answer online and I've already tried:
Verifying the server has the port I'm connecting to opened.
Verifying the client does not block my connection with firewalls, etc.
Creating a new Virtual Host on RabbitMQ and giving permissions to it.
Verifying iptables is not blocking me at the server side.
Nothing seems to work, any ideas?
Full stacktrace here:
This trust manager trusts every certificate, effectively disabling peer verification. This is convenient for local development but prone to man-in-the-middle attacks. Please see http://www.rabbitmq.com/ssl.html#validating-cerficates to learn more about peer certificate validation.
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.security.ssl.InputRecord.readFully(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at java.io.DataOutputStream.flush(Unknown Source)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:147)
at com.rabbitmq.client.impl.SocketFrameHandler.sendHeader(SocketFrameHandler.java:153)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:294)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:63)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:921)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:880)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:838)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:990)
at test.main(test.java:25)
I had the same issue right here: RabbitMQ Connection reset Exception. Solution for Windows was to add backslash in rabbit config file for paths to certs and key.
I don't know if this applies to your situation, but I recently resolved a similar situation while testing RabbitMQ 3.8.3, and the cause was that the key I was referencing was password-protected, but I had failed to provide the password in the RabbitMQ config, like this:
ssl_options.password = password
Unfortunately there was absolutely nothing in the RabbitMQ logs about this, even with the log level set to debug. When testing via various clients, a connection was established, but RabbitMQ immediately sent a connection reset.
I had this exact same error and my issue was in the rabbitmq.conf file. I was trying to use a JKS file for the following ssl options. Generating my own self signed .pem files was able to help fix this. I followed this guide pretty closely https://www.codetd.com/en/article/12031242.
ssl_options.cacertfile = /etc/rabbitmq/ca_certificate.pem
ssl_options.certfile = /etc/rabbitmq/server_certificate.pem
ssl_options.keyfile = /etc/rabbitmq/server_key.pem
I'm using two H2 databases in my Java projects. Recently, I changed my computer and since then I have no problem with connecting to one of those databases using my Java code but problems with the other one. It's exactly the same code (up to PATH_TO_DATABASE) I use to start the connection:
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConfig {
private static java.sql.Connection connection;
public static void init() {
if (connection == null) {
try {
connection = DriverManager.getConnection("jdbc:h2:tcp://192.168.178.50:9092/C:/Users/PATH_TO_DATABASE", "USER", "PW");
} catch (SQLException e) {
System.err.println("SQLException");
e.printStackTrace();
System.exit(0);
}
}
}
[...]
}
This is the stack trace I get:
SQLException
org.h2.jdbc.JdbcSQLException: Connection is broken: "java.net.SocketTimeoutException: connect timed out: 192.168.178.21:9092" [90067-196]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:168)
at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:457)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:334)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:116)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:100)
at org.h2.Driver.connect(Driver.java:69)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at data.DatabaseConfig.init(DatabaseConfig.java:20)
...
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.DualStackPlainSocketImpl.waitForConnect(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 org.h2.util.NetUtils.createSocket(NetUtils.java:103)
at org.h2.util.NetUtils.createSocket(NetUtils.java:83)
at org.h2.engine.SessionRemote.initTransfer(SessionRemote.java:115)
at org.h2.engine.SessionRemote.connectServer(SessionRemote.java:453)
... 8 more
Using the web interface I can connect to both databases easily.
I'm a little bit lost here since I can't figure out what's going wrong with one of the databases. The strange thing is that everything works fine with the other database.
EDIT: I just realized that the IP address in the error message is different from the one in the code (192.168.178.21:9092 vs. 192.168.178.50:9092). Maybe this is th ereason of the error. The one in the code is the correct IP address. Why do I get a different one in the error message? Is that the reason of my problem?
If it's a remote connection, do an ipconfig to find out if the 192.168.x.x. address is changed.
If it's a local connection, you can simplify your URL as
jdbc:h2:~/PATH_TO_DATABASE
I just solved the problem (it was kind of my stupidity): The project couldn't build on the new computer because the H2 jar was not properly included in the build path. That's why eclipse called all the time the old .class file and hence tried to connect to the old computer (192.168.178.21:9092) instead to the new one (192.168.178.50:9092). I didn't realize that eclipse didn't compile and was executing old stuff.
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.