How to connect Sybase ASE with JDBC and SSL connection? - java

I'm trying to establish an SSL connection to a Sybase ASE 16.0 using JDBC driver. On the server, through interactive SQL, I am able to access the ASE server with SSL. I am using Jconnect 4 (jconn4.jar) and JDK 8 with the following connection string: jdbc:sybase:Tds:host:port/dbname?ENABLE_SSL=true. Server certificate imported to the java application trust store using keytool. I have gone through the other question already asked here but it doesn't help me to rectify this problem. Test code is below.
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver");
Connection con = DriverManager.getConnection(
"jdbc:sybase:Tds:host:5000/master?ENABLE_SSL=TRUE", "sa",
"password");
System.out.println("*********Connected**********");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select ##ssl_ciphersuite");
int i = 1;
while (rs.next()) {
System.out.println("Row: " + i);
System.out.println("ID: " + rs.getString(1).trim());
System.out.println(" ");
i = i + 1;
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
My JDBC code throwing below exception.
The connection should be established over the secure network but facing below error.
java.sql.SQLException: JZ00L: Login failed. Examine the SQLWarnings chained to this exception for the reason(s).
at com.sybase.jdbc4.jdbc.SybConnection.getAllExceptions(Unknown Source)
at com.sybase.jdbc4.jdbc.SybConnection.handleSQLE(Unknown Source)
at com.sybase.jdbc4.jdbc.SybConnection.a(Unknown Source)
at com.sybase.jdbc4.jdbc.SybConnection.handleHAFailover(Unknown Source)
at com.sybase.jdbc4.jdbc.SybConnection.<init>(Unknown Source)
at com.sybase.jdbc4.jdbc.SybConnection.<init>(Unknown Source)
at com.sybase.jdbc4.jdbc.SybDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.testing.Test.main(Test.java:41)
I checked the Sybase log see the following error:
kernel SSL or Crypto Error Message: 'The SSL handshake failed. Root error: error:140760FC:SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol'.
I went through the multiple Sybase documentation but no luck. Any help will be much appreciated. Thanks in advance!!

Related

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.

How to connect DB2 database connectivity using java ?

Am trying to connect DB2 database in java but it throwing error, I can't find what issue was that. I added db2jcc.jar and here I show my complete database connectivity code.
public class ConnectionExample {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50000/TestDb";
String user="user";
String password="pass#123";
Connection connection = null;
try {
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
connection = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Am trying to connect DB2 database with the above code but it throws error.
com.ibm.db2.jcc.am.DisconnectNonTransientConnectionException: [jcc][t4][2043][11550][3.63.123] Exception java.net.ConnectException: Error opening socket to server localhost/127.0.0.1 on port 50,000 with message: Connection refused: connect. ERRORCODE=-4499, SQLSTATE=08001
at com.ibm.db2.jcc.am.fd.a(fd.java:321)
at com.ibm.db2.jcc.am.fd.a(fd.java:340)
at com.ibm.db2.jcc.t4.xb.a(xb.java:433)
at com.ibm.db2.jcc.t4.xb.<init>(xb.java:90)
at com.ibm.db2.jcc.t4.a.z(a.java:347)
at com.ibm.db2.jcc.t4.b.a(b.java:1974)
at com.ibm.db2.jcc.am.ib.a(ib.java:691)
at com.ibm.db2.jcc.am.ib.<init>(ib.java:644)
at com.ibm.db2.jcc.t4.b.<init>(b.java:330)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:231)
at com.ibm.db2.jcc.DB2SimpleDataSource.getConnection(DB2SimpleDataSource.java:197)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:472)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:113)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at ConnectionExample.main(ConnectionExample.java:18)
Caused by: java.net.ConnectException: Connection refused: 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 com.ibm.db2.jcc.t4.x.run(x.java:38)
at java.security.AccessController.doPrivileged(Native Method)
at com.ibm.db2.jcc.t4.xb.a(xb.java:419)
... 13 more
Hope Someone helps me to find out the solution. Thanks
Actually the port 50000 is not opened that is the reason I got the error after change that port to 51020 it works fine also it connects with database.
String url="jdbc:db2://localhost:51020/TestDb";
Thanks
Cause
A possible cause for this problem is that TCP/IP is not properly enabled on your DB2 database server.
Resolving the problem
Use the db2set DB2COMM command from the DB2 command window to start the TCP/IP connection:
db2set DB2COMM=protocol_names
For example, to set the database manager to start connection managers for the TCP/IP communication protocols, enter the following commands:
db2set DB2COMM=tcpip
db2stop
db2start
Source: https://www-304.ibm.com/support/docview.wss?uid=swg21403644

Port number is not correct while connecting to sql server

I am trying to connect to SQL Server as follows from Netbeans. I have sqljdbc4.jar in my Libraries forlder of the project.
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connRemoteforGlobal = java.sql.DriverManager.getConnection("jdbc:sqlserver://xx.xx.x.xxx:1433/test",RemoteSQLServerUser,RemoteSQLServerPass);
if(connRemoteforGlobal != null)
{
System.out.println("Connection Successful !");
}
}
catch(SQLException ex2){
ex2.printStackTrace();
System.out.println("Error Trace in Connection : " + ex2.getMessage());
}
And getting the following error:
Is there any additional settings required in netbeans or in my connection? Port number?
Error Trace in Connection : The port number 1433/test is not valid.
com.microsoft.sqlserver.jdbc.SQLServerException: The port number 1433/test is not valid.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:691)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at mypackage.myclass.call(myclass.java:408)
at mypackage.myclass.call(myclass.java:25)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1259)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
It should be:
jdbc:sqlserver://xx.xx.x.xxx:1433;databaseName=Test
This is the format:
jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
http://technet.microsoft.com/en-us/library/ms378428.aspx
Look at http://technet.microsoft.com/en-us/library/ms378988.aspx for properties. Anyway, 1433 seems to be the default port number so it is not necessary to specify it.

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";

Create a jTDS connection string

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.

Categories