I can't connect to Microsoft SQL Server through Java - java

I have SQL Server installed through Docker on Windows and I can connect to the database with VS Code through the SQL Server extension, but I can't get it to connect in my Java code. I get the 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: "PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target".
ClientConnectionId:018acf50-eefc-41e8-842a-6b7ef89a84d9
I installed the JDBC driver through Maven:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>11.2.2.jre17</version>
</dependency>
The code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectToMSSQL {
public static void main(String[] args) {
// Set connection parameters.
String hostName = "localhost";
String dbName = "testdb";
String user = "SA";
String password = "<password>";
String url = String.format("jdbc:sqlserver://%s;databaseName=%s;user=%s;password=%s", hostName, dbName, user, password);
// Connect to the database.
try (Connection con = DriverManager.getConnection(url)) {
System.out.println("Connection established.");
} catch (SQLException e) {
System.out.println("Connection failed.");
e.printStackTrace();
}
}
}

Related

Access Denied from jdbc to google cloudsql

I am trying to connect to cloudmysql gcp instance using jdbc connection string with ssl enabled. It gives me access denied for user. I followed the following steps
I got the client-key, client-cert, server-ca from cloudmysql instance.
Generated the truststore.jks by keytool from server-ca.pem.
Now below is the snippet. When running getting access denied for user.let me know if anything is missing
import java.sql.*;
import java.util.Properties;
class JdbcTest{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
System.setProperty("javax.net.ssl.trustStore","D://truststore.jks");
System.setProperty("javax.net.ssl.trustStorePassword","password");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/dbname?verifyServerCertificate=true&useSSL=true&requireSSL=true", "username", "password");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("SHOW DATABASES");
while(rs.next())
System.out.println("test");
con.close();
}catch(Exception e){ e.printStackTrace();}
}
}

Cassandra jdbc connection with Authentication

I am trying to connect to the Cassandra using cdata jdbc connector. However, I cannot find how to provide username and password in connection url. Here are my java code.
package com.dremio.exec.store.jdbc.conf;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestConnection {
public static void main(String[] args) throws Exception {
Connection con = null;
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra://localhost:9160");
String query = "SELECT * FROM emp";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("emp_id"));
System.out.println(result.getString("emp_name"));
System.out.println(result.getString("emp_city"));
}
con.close();
}
}
Currently, I am providing url as without Authentication. How can i provide username and password there.
CData's (poor) documentation lists User and Password as available properties to add to a JDBC connection string. You can add these with your username and password to authenticate:
con = DriverManager.getConnection(
"jdbc:cassandra://localhost:9160;User=ayush;Password=yourpwd");
You could also add them as properties, as detailed in their Connecting From Code examples:
Properties prop = new Properties();
prop.setProperty("Port","9042");
prop.setProperty("Server","127.0.0.1");
prop.setProperty("User","ayush");
prop.setProperty("Password","yourpwd");
Connection conn = DriverManager.getConnection("jdbc:cassandra:",prop);
Also, unless you're using an old Cassandra cluster or 3.x cluster with Thrift enabled, 9160 isn't going to work. In fact, the Thrift project hasn't had a pull request in a few years now, so I would suggest moving away from it and using the native binary protocol on 9042.

How to connect to Oracle Cloud DDBB using JDBC Thin Driver and Oracle Wallet

I am following the guide to connect from a java application using the IDE IntelliJ to an Oracle Cloud Database.
I meet the prerequisites since:
I have a Database in Oracle Cloud service
I downloaded the wallet and I placed the files in the src directory of my workspace.
I am using last JDK 14
I am using the ojdbc8.jar
And I downloaded as well the oraclepki, osdt_cert, and osdt_core jars, all of them added as java libraries in my test project
The recommended BD_URL is never working. I always get: java.net.UnknownHostException and oracle.net.ns.NetException: The Network Adapter could not establish the connection
DB_URL= "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=testgerard_high)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=testgerard_high)))"
Then I found in Oracle support that it could be added to the wallet directory, but the same issue.
DB_URL= "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=testgerard_high)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=testgerard_high))(SECURITY = (MY_WALLET_DIRECTORY = src\\Wallet_testGerard)))"
If I switch to a connection string using 18.3 JDBC driver which should work for my settings, then I get the error: Invalid connection string format, a valid format is: "host:port:sid"
DB_URL="jdbc:oracle:thin:#testgerard_high?TNS_ADMIN=src\\Wallet_testGerard";
Finally, I have seen here a way to inform the wallet folder out of the BD_URL so I do not get the invalid format exception:
System.setProperty("oracle.net.tns_admin","src\\Wallet_testGerard");
Now it is trying to connect but it fails after 60 seconds with the exception:sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
I adapted an oracle example, here is my code:
import java.sql.SQLException;
import java.sql.DatabaseMetaData;
import oracle.jdbc.pool.OracleDataSource;
import oracle.jdbc.OracleConnection;
public class OracleDataSourceSample
{
final static String DB_URL="jdbc:oracle:thin:#testgerard_high";
//final static String DB_URL="jdbc:oracle:thin:#testgerard_high?TNS_ADMIN=src\\Wallet_testGerard";
//final static String DB_URL= "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(HOST=testgerard_high)(PORT=1521)(PROTOCOL=tcp))(CONNECT_DATA=(SERVICE_NAME=testgerard_high))(SECURITY = (MY_WALLET_DIRECTORY = src\\Wallet_testGerard)))";
final static String DB_USER = "hr";
final static String DB_PASSWORD = "hr";
public static void main (String args[]) throws SQLException, ClassNotFoundException {
System.setProperty("oracle.net.tns_admin","src\\Wallet_testGerard");
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleDataSource ods = new OracleDataSource();
ods.setURL(DB_URL);
ods.setUser(DB_USER);
ods.setPassword(DB_PASSWORD);
// With AutoCloseable, the connection is closed automatically.
try (OracleConnection connection = (OracleConnection)
ods.getConnection()) {
// Get the JDBC driver name and version
DatabaseMetaData dbmd = connection.getMetaData();
System.out.println("Driver Name: " + dbmd.getDriverName());
System.out.println("Driver Version: " +
dbmd.getDriverVersion());
System.out.println("Database Username is: " +
connection.getUserName());
}
}
}
Tested with stand alone jdk 8 and jdk 14 as well as Intellij Community edition(first run firewall blocked intellij).
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import oracle.jdbc.pool.OracleDataSource;
import oracle.jdbc.OracleConnection;
import java.sql.DatabaseMetaData;
public class SalesConnection
{
final static String DB_URL="jdbc:oracle:thin:#oci_adw_high";
final static String DB_USER = "xxxx";
final static String DB_PASSWORD = "xxxxx";
public static void main (String args[]) throws SQLException, ClassNotFoundException {
System.setProperty("oracle.net.tns_admin","C:\\app\\oracle\\product\\19\\dbhome_1\\network\\admin");
System.setProperty("oracle.jdbc.fanEnabled","false");
Class.forName("oracle.jdbc.driver.OracleDriver");
OracleDataSource ods = new OracleDataSource();
ods.setURL(DB_URL);
ods.setUser(DB_USER);
ods.setPassword(DB_PASSWORD);
// With AutoCloseable, the connection is closed automatically.
try (OracleConnection connection = (OracleConnection)
ods.getConnection()) {
// Get the JDBC driver name and version
DatabaseMetaData dbmd = connection.getMetaData();
System.out.println("Driver Name: " + dbmd.getDriverName());
System.out.println("Driver Version: " +
dbmd.getDriverVersion());
System.out.println("Database Username is: " +
connection.getUserName());
printSales(connection);
}
}
public static void printSales(Connection connection) throws SQLException {
// Statement and ResultSet are AutoCloseable and closed automatically.
try (Statement statement = connection.createStatement()) {
try (ResultSet resultSet = statement
.executeQuery("select /* Java Console */PROD_ID, CUST_ID from sales fetch first 10 rows only ")) {
System.out.println("PROD_ID" + " " + "CUST_ID");
System.out.println("---------------------");
while (resultSet.next())
System.out.println(resultSet.getString(1) + " "
+ resultSet.getString(2) + " ");
}
}
}
}
Try to run this code change table and column names
Source of this code
Edit:
Compiling and executing from command prompt
javac -cp "C:\ojdbc8-full\*;" SalesConnection.java
java -cp "C:\ojdbc8-full\*;" SalesConnection
ojdbc8-full.zip contains oraclepki.jar, osdt_core.jar and osdt_cert.jar which are required for connecting to Oracle autonomous database. However, you can get JDBC driver along with other additional libraries using these maven co-ordinates.
<dependencies>
<dependency>
<groupid>com.oracle.database.jdbc</groupid>
<artifactid>ojdbc8-production</artifactid>
<version>19.7.0.0</version>
<type>pom</type>
</dependency>
</dependencies>
Refer to the Maven Central Guide for more information

Getting SSL error while trying to connect to SQL-Server 2014

Getting error while trying to connect to SQL Server 2014.
I'm using JRE7 and sqljdbc4-4.0.jar
here is my java code:
package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Testing {
public static void main(String[] args) {
String url = "jdbc:sqlserver://localhost:1433;databaseName=test;encrypt=false";
String user = "sa";
String pass = "";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException: " + e);
}
try (Connection con=DriverManager.getConnection(url,user, pass);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM exts WHERE ext = 1001");){
if(rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
} else {
System.out.println("NOT_FOUND");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Here is the full stack trace:
java.ext.dirs: C:\Cisco\CallStudio\eclipse\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext
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 did not return a response. The connection has been closed. ClientConnectionId:dd9cabc2-3683-4a14-857c-eeefd2751853".
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:1667)
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1668)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1323)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
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 com.test.Testing.main(Testing.java:32)
Caused by: java.io.IOException: SQL Server did not return a response. The connection has been closed. ClientConnectionId:dd9cabc2-3683-4a14-857c-eeefd2751853
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.ensureSSLPayload(IOBuffer.java:651)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.readInternal(IOBuffer.java:708)
at com.microsoft.sqlserver.jdbc.TDSChannel$SSLHandshakeInputStream.read(IOBuffer.java:700)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.readInternal(IOBuffer.java:895)
at com.microsoft.sqlserver.jdbc.TDSChannel$ProxyInputStream.read(IOBuffer.java:883)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:442)
at sun.security.ssl.InputRecord.read(InputRecord.java:480)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1618)
... 7 more
SSL exceptions occur when TLS version mismatch. As you are using Java 7, Try to add sslProtocol=TLSv1.2 to your connection string.

Windows authentication failing when connecting to sql server using JDBC

I have SQL server on a machine under the domain DOM005 and I am trying to connect to it using JDBC driver from my local machine that is in another domain. I am using windows authentication for the connection through domain administrator account.
I cannot use "integratedSecurity=true" in my connection URL since both machines are in different domain. Hence I use "authentication=ActiveDirectoryIntegrated" but I am getting the following error:
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'DOM005\administrator'. ClientConnectionId:84224bcd-d2f1-4386-aadf-397c1ef3eadf
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:251)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:3077)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2360)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:43)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2346)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:6276)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1793)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1404)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1068)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:904)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:451)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1014)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at TestJDBCsqlServer.main(TestJDBCsqlServer.java:23)
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestJDBCsqlServer {
private static final String SQLSERVER_URL_NTLM = "jdbc:sqlserver://10.20.13.4:1433;databaseName=DB1;authentication=ActiveDirectoryIntegrated";
public static void main(String[] args) throws Exception {
boolean isNTLM = true;
Connection conn = null;
Statement stmt = null;
if(isNTLM){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(SQLSERVER_URL_NTLM, "DOM005\\administrator", "abc");
stmt = conn.createStatement();
ResultSet set = stmt.executeQuery("select 1");
System.out.println("NTLM connection is successful");
set.next();
System.out.println(set.getString(1));
}finally{
if(stmt != null)
stmt.close();
if(conn!=null)
conn.close();
}
}
}
}
Can anyone help me resolve the issue?

Categories