Create a jTDS connection string - java

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.

Related

Exception in GridDB JAVA API

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

Local and Remote connection pools, Java DBCP

I have the following use-case:
I have a system that needs to use two different connection pools, One is for 'local' database (Meaning a database running on the local machine) and the other one is a 'remote' database. (Meaning a database that is running on a remote different server)
The remote database is a configuration sharing database, while the local one is has different kinds of data.
I've created two classes in order to connect to those datababase:
public class ConnectionPool {
private static BasicDataSource ds = createNewDatasource();
private static BasicDataSource createNewDatasource() {
BasicDataSource ds = new BasicDataSource();
String url = "jdbc:mysql://127.0.0.1:3306/SOME_DB"
ds.setUrl(url);
ds.setUsername(...);
ds.setPassword(...);
return ds;
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
The other class looks exactly the same, Only it's called RemoteConnection and the url is changed to:
String url = "jdbc:mysql://<REMOTE_IP>:3306/SOME_DB_2"
Running the above classes, I keep receiving the following message in my logs:
ERROR (RemoteConnection.java:40) - Failed on getConnection
java.sql.SQLException: Cannot create PoolableConnectionFactory (Access denied for user '...'#'<MACHINE_LOCAL_IP>' (using password: YES))
at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2291)
at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2038)
at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)
at Censored.RemoteConnection.getConnection(RemoteConnection.java:59)
...
Caused by: java.sql.SQLException: Access denied for user '...'#'<MACHINE_LOCAL_IP>' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
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:2188)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2219)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2014)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:776)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.GeneratedConstructorAccessor31.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:57)
at java.lang.reflect.Constructor.newInstance(Constructor.java:437)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
at org.apache.commons.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:39)
at org.apache.commons.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:256)
at org.apache.commons.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2301)
at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2287)
...
Firstly, The error above is weird. I've never used the machine local IP. So I don't understand where it came from. In addition, It doesn't seems like a privilege problem since I've tried logging into remote database through cli, using:
mysql -u'...' -p'...' -h <REMOTE_IP> SOME_DB_2
And it connected successfully. It smells to me like a JDBC Driver or connection definition problem but I can't seem to find the problematic spot.
Any idea what I'm doing wrong?
I've found the problem. It was an SSL issue.
The user I've used had to connect with SSL certificate.
That's also the reason why I've seen the local machine IP in the error.
A way to check is:
Select * from mysql.user where user='...';
What I've found was that:
ssl_type != ''
So I had to define:
jdbc:mysql://<REMOTE_IP>:3306/SOME_DB_2&useSSL=true
Configure the relevant certificates, and all was well.

How to connect to Azure SQL database with jTDS

I try to connect to Azure SQL with:
import java.sql.*;
public class ExampleJTDS {
public static void main(String[] args) {
// Setting.
String connectionUrl = "jdbc:jtds:sqlserver://SERVER.database.windows.net:1433/DATABASE;ssl=off";
String user = "USER#SERVER";
String pass = "PASSWORD";
// Declare the JDBC object.
Connection conn = null;
try {
// Establish the connection.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(connectionUrl, user, pass);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
But I am getting:
java.sql.SQLException: I/O Error: DB server closed connection.
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2481)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:632)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:371)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at run.ExampleJTDS.main(ExampleJTDS.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
If I force the encryption by substituting ssl=off with ssl=require, I am getting:
java.sql.SQLException: Network error IOException: Connection reset
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:436)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at run.ExampleJTDS.main(ExampleJTDS.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Interestingly, I can connect to the database from the same computer and with the same JDBC driver with SQuirreL SQL (although without SSL - SQuirreL SQL manages to put the credentials into the first TDS packet and Azure accepts that). Hence, the problem should not be in the setting of firewalls.
Metadata:
Server: Azure V12
Driver: jtds-1.3.1
JRE: 1.8.0_72-b15 (from Oracle)
_JAVA_OPTIONS: -Djsse.enableCBCProtection=false
security.provider.1: sun.security.provider.Sun
OS: OS X 10.11.5
SQuirreL SQL: 3.7.1
How can I connect to Azure SQL from Java?
Per my experience, I think the issue was caused by the connection string which is the variable connectionUrl of your code. I have answered your similar question of the SO thread, please see How to connect to Azure SQL with JDBC.
However, using jTDS instead of Microsoft JDBC driver for SQL Server has a little difference, you can refer to a note in the step 3 of the tutorial to know it. As reference, I post the contento of the note here.
Note:
If you are using the JTDS JDBC driver, then you will need to add "ssl=require" to the URL of the connection string and you need to set the following option for the JVM "-Djsse.enableCBCProtection=false". This JVM option disables a fix for a security vulnerability, so make sure you understand what risk is involved before setting this option.
Hope it helps. Any concern, please feel free to let me know.

SQL-Database and Java

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!

JDBC DB2 can not connect (SQLSTATE=08S01)

I want to connect both Oracle and DB2 databases for some reason using JDBC. In main class when I try to connect Oracle, Connection is successfull but DB2 connection is NOT successfull giving this error: "Yuva acilirken hata olustu" means "Socket can not be opened" . What can be the problem??? Oracle works but DB2 does not work. I checked all password, usernames, host names and ports again and again for DB2.
COM.ibm.db2.jdbc.DB2Exception: [IBM][JDBC Driver] CLI0616E Yuva açılırken hata oluştu. SQLSTATE=08S01
at COM.ibm.db2.jdbc.net.SQLExceptionGenerator.socketException(Unknown Source)
at COM.ibm.db2.jdbc.net.DB2Connection.create(Unknown Source)
at COM.ibm.db2.jdbc.net.DB2Connection.<init>(Unknown Source)
at COM.ibm.db2.jdbc.net.DB2Driver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:590)
at java.sql.DriverManager.getConnection(DriverManager.java:232)
To get connection, I write these in main,
connORA = DirectConnection.getOracleConnection();
connDB2 = DirectConnection.getDB2Connection();
My Connection Class I defined Oracle COnnection and DB2 connection as follows: (Maybe there is a problem in DB2 Connection Method? Oracle connects succesfully)
public static Connection getOracleConnection() throws SQLException, ClassNotFoundException{
return getConnection("oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:#host:port:name", "username", "password");}
public static Connection getDB2Connection() throws SQLException{
return getConnection("COM.ibm.db2.jdbc.net.DB2Driver", "jdbc:db2://host:port:name","username", "password");}
Firstly, as #ThePhantom05 mentioned, you should be using the JCC driver, not the older net driver. The correct URL pattern for a DB2 JDBC connection will be jdbc:db2://host:port/database_name
Try using this as your driver instead:
String driver = "com.ibm.db2.jcc.DB2Driver";

Categories