Java7 sqljdbc4 - SQL error 08S01 on getConnection() - java

I'm trying to write a really simple GUI app for inserting some records
into a database, and reading back some records (nothing fancy, just 1 table with 3 rows, no relations).
The source...
package EntryProg;
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class CourseDataEntryHandler
{
private Connection connect;
private CallableStatement callState;
private ResultSet rSet;
private SQLServerDataSource dSource;
public CourseDataEntryHandler()
{
rSet = null;
callState = null;
dSource = new SQLServerDataSource();
dSource.setUser(REDACTED);
dSource.setPassword(REDACTED);
dSource.setServerName(REDACTED);
dSource.setPortNumber(REDACTED);
dSource.setDatabaseName(REDACTED);
dSource.setEncrypt(true);
dSource.setTrustServerCertificate(true);
try
{
Error here
connect = dSource.getConnection();
end error
}
catch (SQLServerException e)
{
//TODO Figure out how to handle -- logging for now, console
do
{
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
System.out.println(e.getSQLState());
e = (SQLServerException) e.getNextException();
} while (e != null);
System.out.println("END");
System.out.println();
}
}
I get the following error...
(code)0
(message)SQL Server did not return a response. The connection has been closed.
(state)08S01
I've verified that the user,pass,server name,port, and DB name are all accurate.
If I change the username to a non-valid one, I get a "could not log in" error reported back so I know I'm hitting the server.
I've not been able to fully connect once, so I know it's not a "too many connections" issue, as the only person currently logged into the server is me via sql management studio. It doesn't work when I log out of that either so definitely not a connections # issue.
The applications user has datareader/datawriter permissions as well.
(I'm using Eclipse, if that matters. And am referencing the sqljdbc4.jar library).
I'm at a loss as to where to go with troubleshooting this. Any help would be greatly appreciated.
EDIT
Update - I've also tried a connection string and using DriverManager.getConnection(connString) to set the connection, that didn't work either. The result is the same.
Also, SQL server 2008 r2 is the sql server version I'm using.
EDIT
I wrote a quick C# program to test the connection, sure enough the connection works fine in .net, unfortunately I have to use java for this project (it's a project I've chosen to do on my own for a class, only requirement is it be in Java...teacher has no clue what's going on either).

Comment the line with setEncrypt(true):
...
dSource.setDatabaseName(REDACTED);
//dSource.setEncrypt(true);
dSource.setTrustServerCertificate(true);
...
You might have trouble with the encryption setting. From the setEncrypt(...) documentation:
If the encrypt property is set to true, the Microsoft SQL Server JDBC Driver uses the JVM's default JSSE security provider to negotiate SSL encryption with SQL Server. The default security provider may not support all of the features required to negotiate SSL encryption successfully. For example, the default security provider may not support the size of the RSA public key used in the SQL Server SSL certificate. In this case, the default security provider might raise an error that will cause the JDBC driver to terminate the connection. In order to resolve this issue, do one of the following:
Configure the SQL Server with a server certificate that has a smaller RSA public key
Configure the JVM to use a different JSSE security provider in the "/lib/security/java.security" security properties file
Use a different JVM
Update
With Java versions 1.6.0_29 and 7.0.0_1 Oracle introduced a security fix for the SSL/TLS BEAST attack that very likely will cause the very same problem. The above security fix is known to make trouble for database connections to MSSQL Server with both the jTDS driver and the Microsoft driver. You can either
decide not to use encryption by not using setEncrypt(true) (as specified above)
or, if it is enforced by MSSQL Server, you could turn off the Java fix in your JVM by setting the -Djsse.enableCBCProtection=false system property. Be warned, it will affect all SSL connections within the same VM.

Sometimes, the engine configuration is modified in such a way it doesn't accept external connections. After some research, the following worked for me:
Open SQL Server Configuration Manager
Get to SQL SERVER Network Configuration
MSSQLSERVER Protocols (Double click)
View TCP/IP (must be enabled) (Open)
Go to tab "IP Addresses"
Type into "TCP Port" :1433
The enabled and activated options must be Enabled: Yes
Restart the service

Related

SQL connectivity exceptions - The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption

We are observing SQL Server connection is getting dropped with the below error
: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "SQL Server returned an incomplete response. The connection has been closed. ClientConnectionId:b928e7b0-689b-40f8-be3e-158261d0a84a".
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "SQL Server returned an incomplete response. The connection has been closed. ClientConnectionId:b928e7b0-689b-40f8-be3e-158261d0a84a"
we are using sqljdbc42.jar in our application , MSSQL Server is MS SQL SERVER 2014 SP3 java version is 1.8
we cannot set to TLSv1 as mentioned in one of the resolution here SQL Server JDBC Error on Java 8: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption,
as a dependent application needs TLSv2 for it to work.
As per microsoft, jdbc 4.2 jar should resolve it , but we are already on it. https://blogs.msdn.microsoft.com/dataaccesstechnologies/2016/11/30/intermittent-jdbc-connectivity-issue-the-driver-could-not-establish-a-secure-connection-to-sql-server-by-using-secure-sockets-layer-ssl-encryption-error-sql-server-returned-an-incomplete-respons/
Please share suggestions or inputs you may have implemented for a similar problem.
Thanks,
Nivedita
Did you try the registry change mentioned in option 2 of the microsoft article?
Disable DHE cipher suites :
Warning: If you use Registry Editor incorrectly, you may cause serious problems that may require you to reinstall your operating system. Microsoft cannot guarantee that you can solve problems that result from using Registry Editor incorrectly. Use Registry Editor at your own risk.
Open Registry Editor.
Access key exchange algorithm settings by navigating to the following registry location:HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\KeyExchangeAlgorithms
Select the Diffie-Hellman sub key (if it does not exist, then create
it).
Set the Enabled DWORD registry value to 0 (if it does not
exist, then create it).
Exit Registry Editor.
Impact of the workaround: Encrypted TLS sessions that rely on DHE keys will no longer function unless alternative failover options have been implemented.
https://technet.microsoft.com/en-us/library/security/ms15-055.aspx

Connect Metabase to Sql Server

I installed Java on my Windows 10 machine and downloaded Metabase.jar, and ran it.
Now I could access metabase at localhost:3000
But I'm unable to setup my SQL Server Database as Data reference.
I'm either getting:
Couldn't connect to the database. Please check the connection details.
or
Timed out after 5000 milliseconds.
Anyone who has done Metabase - SQL Server connection successfully?
Currently, as of Metabase version 0.30.x the answer depends on if you can use a user configured directly on SQL Server or not:
The easier option to setup is with a user configured directly on SQL Server. Then config is just Name: (anything), Host: (full name), Database Name, Username, Password as you would expect. (I believe you should NOT fill in the Windows domain).
On Windows only you can also use native integrated authentication with sqljdbc_auth.dll, just specify integratedSecurity=true connection property (and optionally authenticationScheme=NativeAuthentication). I found if I dropped the x64 sqljdbc_auth.dll in my <java path>\jre\bin folder it was picked up. Metabase config as in the screenshot below, apart from dropping authenticationScheme=JavaKerberos
The cross platform authenticationScheme=JavaKerberos option to use Windows Authentication with a domain user is still doable, but harder. It's these steps:
Create a krb.conf and verify login works with <Java path>\bin\kinit.exe [user]. Here's a template edited to match the Metabase database setup in the screenshot below.
Start the Metabase.jar file with parameters to load the krb.conf. It works for me with java -Djava.security.krb5.conf=c:/<path>/kerberos/krb.conf -jar metabase.jar.
Now configure the database settings in Metabase according to the screenshot below
Moment of truth! ...
Optional: Still not working? Maybe your SQL Server isn't configured for Kerberos? Maybe you need SPN setup? Maybe you need to specify a java.security.auth.login.config (I have not experienced any of that myself, only thing I can offer is you scroll to the bottom of this post and dive in then edit your question with where you got to and what config you have)
Metabase SQL Server setup using Kerberos:
For background, current (August 2018) very long :| sum up with lots of links of how to connect to SQL Server is here in a Metabase discussion topic Note: In v0.30.0 an issue with dynamic port handling (particularly for people using named instances) was fixed.
Related: A neat StackOverflow answer on Kerberos on a Mac
If you are connecting to a "Named Instance" ({SERVER_NAME}/{INSTANCE_NAME}) instead of "Default Instance" ({SERVER_NAME}), your server may be configured to use Dynamic Port.
A quick dirty fix is you can find the current port with below scripts and then use it on Metabase connection parameters. But this port most probably will change when service restart occurs.
SELECT DISTINCT
local_tcp_port
FROM sys.dm_exec_connections
WHERE local_tcp_port IS NOT NULL
or
USE master
GO
Xp_readerrorlog
(look for "Server is listening on ..." line)
A Cleaner way is setting port for your instance by "SQL Server Configuration Manager" - "SQL Server Network Configuration" - "TCP/IP" - Right Click properties - "TCP Dynamic Ports" (There should be 0 and it should be deleted) and "TCP Port" (New default port should be set here). And also "SQL Server Browser" service should run. A more detailed explanation is here

Android + JDBC: No route to host (it works on the desktop, why not on android?)

I've searched through the site and haven't quite found a post that answers my problem.
I wrote a desktop application (Java/swing/JDBC) to connect to a local database via JDBC. This database is hosted on an IBM i-series (AS400) (though I'm quite certain this isn't an as400-only problem) and is only available on the internal network. I'm working on translating that application into an android app to be used onside in the warehouse via wireless connection.
I have my JDBC connection in it's own thread. The app asks the user for username/password before attempting a connection. The connection fails every time with the same message: java.sql.SQLException: The application requester cannot establish the connection. (No route to host)
Here is the offending code:
try
{
// Use the AS400 driver.
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
// Now connect
connection = DriverManager.getConnection(
"jdbc:as400://" + IP_ADDRESS + "/" + SCHEMA +
";naming=sql;errors=full",
USER_ID, PASSWORD);
System.out.println("Connection established using the AS400 driver(s)");
}
catch(Exception as400)
{
String message = "Error setting driver and connection using\n "
+ "the AS400 drivers. The error message is as follows:\n "
+ as400.getMessage();
System.out.println(message);
throw new Exception(message);
}
It registers the driver then hits No route to host, pauses for a second, then throws an error, completely stalling the device instead of letting my error handler safely close the app.
I have double (triple) checked to ensure the credentials are correctly passed and the IP and schema are both correctly set. This code is a direct copy of my desktop code. The only difference is I use a jar optimized for android instead of the desktop. The jar simply contains a translation layer between native AS400 code and Java, but works the same as any SQL jar.
This is our primary database server used throughout the entire company. It is always available and SQL is enabled on it. I am testing this using a physical android device (not an emulated one) and it is connected to our internal wireless network.
Any suggestions on how to fix this or even a direction to look in? Why is there such a difference between the desktop and my android despite both using JDBC? Do I need to do something special for address resolution or something similar? Google-fu is failing me badly. Thanks for your help!
It's not uncommon for wireless traffic to be restricted due to corporate security policies.
Verify that you can connect to DRDA (tcp port 446) on the IBM i from the device on the wireless network.
See TCP/IP Ports Required for iSeries Access for Windows for more information.
JTOpen/Toolbox has a proxy mode if security requirements prevent allowing direct access to the IBM i.
The lightweight version of the JTOpen/Toolbox jar's are also more suited to installation in a cpu and memory restricted environment such as an Android device.
The full JTOpen/Toolbox can be run as a proxy server as follows:
java -cp jt400.jar com.ibm.as400.access.ProxyServer -verbose -port 3470
Add the proxy server option to your connection string:
jdbc:as400:<url>;proxy server=<proxy server address:port>

Trying to connect to SQL Server 2008 Express database with SQL Server authentication always result in "Login failed for user '...'."

I am using jTDS to connect a Liferay instance to an SQL Server 2008 Express server using the SQL Server authentication (instead of the Windows' auth method). I have something like this in my portal-ext.properties:
jdbc.default.driverClassName=net.sourceforge.jtds.jdbc.Driver
jdbc.default.url=jdbc:jtds:sqlserver://127.0.0.1:1433/somedb
jdbc.default.username=someuser
jdbc.default.password=somepassword
(For those that do not know Liferay, it is somewhat alike to call
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection("jdbc:jtds:sqlserver://127.0.0.1:1433/somedb",
"someuser", "somepassword");
However, although I pass the correct username and password, it keeps going wrong with the message Login failed for user 'someuser'. I am dead sure the server login, the database user and the database exists and are well configured.
What can be wrong?
Well, I suppose there can be infinite reasons for such an error. In my case, nonetheless, the solution was the following:
Enable the TCP/IP connection in SQL Configuration Manager.
Open the SQL Server Management Studio (if you do not have it installed, install it; it can have its own pitfalls, however).
Right-click on the database server (as in the picture below) and click in Properties.
Select the Security option and mark SQL Server and Windows authentication mode. Click in OK.
Open the SQL Server Configuration Manager and restart the SQL Server service.
After this, I got my connections without problems. This article helped me a lot.

jdbc.SQLServerException: Login failed for user for any user

I trying to test the connection with my local sql DB. I have this code:
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=SocialFamilyTree;user=SOSCOMP");
}catch(Exception e){
System.out.println("Couldn't get database connection.");
e.printStackTrace();
}
I tried many users. my windows user is SOSCOMP and doesn't have a password. I also know that SQL 2008 create users as "sys" "dbo", I tried these too. I'm always getting:
Couldn't get database connection.
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'SOSCOMP'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2532)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:1929)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:1917)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1061)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:243)
at FT_Receiver.FT_Receiver.main(FT_Receiver.java:12)
Any ideas?
Thanks
If you try to connect with database which is using windows authentication, you can use 'integratedSecurity' option in your connection string.
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=SocialFamilyTree;integratedSecurity=true;");
Having been through this very recently the steps I took to solve pretty much the same problem were
use SQL Server Management Studio to log in with the desired account and confirm access to read (and write if necessary)
Use SQL Server Configuration Manager to confirm that the server instance is listening on the IP address being targetted
Disable the firewall to check that isn't getting in the way (and add an exception if necessary for future use)
The absolute kicker for me was understanding what IP addresses and ports the instance was set to listen on so that when I constructed the connection string the connection wasn't being rejected.
Also, if you want to connect using Windows logins you need to ensure the SQL instance is configured for mixed mode authentication (i.e. to allow Windows and SQL logins)
Since you get this error,the Sql server correctly listens to the port.
Open Sql Server Management Studio connect to your Server.
right click on the server's icon and choose properties.
Go to the security tab and tick Sql Server and Windows
Authentication mode.
If you want to define a user,go from the tree, to Security->Logins,right click on logins folder and click "New Login".
Now your server should work with this Url String.
Use the log file of the Server that may help you understand its working.
Re: Did it. still WARNING: Failed to load the sqljdbc_auth.dll cause :- no sqljdbc_auth in java.library.path – Mike Oct 7 at 14:03
you have to add the path to sqljdbc_auth.dll by adding this under VM arguments in Eclipse or commandline if you're running from the shell:
-Djava.library.path="\MS SQL Server JDBC Driver 3.0\sqljdbc_3.0\enu\auth\x86"
that's if you're running 32 bit Windows. else the final subdir changes accordingly.
I think this might be a better answer though, to setting up SQL Server user based authentication:
Connecting SQL Server 2008 to Java: Login failed for user error
(I try to summarize it here: http://silveira.wikidot.com/sql-server)
I also faced the same issue, In my case the following things are configured wrongly
Two SQL (versions) servers are running in my system --> Sol: Please check ourselves which server we are pointing.
Ports are configured as dynamic --> Sol: we should set port 1433 and dynamic port should be 0, if we are connected to specific port.
While creating the new login (user) I have selected the option " change password after first login "--> Sol: we should not select this option while creating the new login, if we are trying connecting from some other service like Openfire.

Categories

Resources