Cassandra jdbc connection with Authentication - java

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.

Related

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

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?

Android-MysqlConnectivity in eclipse

I am new to android, So i need a basic knowledge,How to connect to the database and Select some of the values from it.
These are all the following steps i have already completed by watching and reading some online tutorials.
Created a New ANDROID Project Named And2.
Created a New JAVA Project named MYSQLConnection which is used to store the database connection.
I have Downloaded mysql-connector-java-5.1.34 file Online and added it.
I have attached the Screen Shot the total overview of my eclipse.
Now i just needed to access the database in And2 and Write a Simple Select Query So that i can make sure that connection is created.
Shown below is the Java file for DB Connection.
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import com.mysql.jdbc.*;
//import com.mysql.jdbc.Connection;
//import com.mysql.jdbc.Statement;
public class Main {
public static void main(String[] args) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
try
{
String connectionUrl = "jdbc:mysql://localhost:3306/testdatabase";
String connectionUser = "root";
String connectionPassword = "12345";
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
//Statement stmt = conn.createStatement();
// ResultSet reset = stmt.executeQuery("select * from TableName");
//
// //Print the data to the console
// while(reset.next()){
// Log.w("Data:",reset.getString(3));
//
// }
}
catch ( SQLException err )
{
System.out.println("Database connection failed");
}
}
}
Any Help appreciated.

com.mysql.jdbc.Driver showing null on the browser

Hi I am having some trouble while I am trying to access my database. The connection to the database is not getting established.
In the web browser I am getting the following output:
In Connection Db
In try before registering driver
null
Below is the code snippet I am using to establish the connection.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ConnectionDB extends HttpServlet {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Data";
// Database credentials
static final String USER = "root";
static final String PASS = "";
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
pw.println("<h2>In Connection Db</h2>");
try {
//STEP 2: Register JDBC driver
pw.println("<h2>In try before registering driver</h2>");
Class.forName("com.mysql.jdbc.Driver");
pw.println("<h2>In try</h2>");
//STEP 3: Open a connection
con = DriverManager.getConnection(DB_URL,USER,PASS);
pw.println("<h2>After connection</h2>");
stmt = con.createStatement();
My classpath variable is set as follows
CLASSPATH = C:\Database\mysql-connector-java-5.1.27\mysql-connector-java-5.1.27-bin.jar;
Thanks in advance.
You may want to specify the port number for the JDBC URL. For MySQL this is usually 3306. So, your JDBC URL should be:
jdbc:mysql://127.0.0.1:3306/Data
However, you may find that the root cause if because your mysql connector is not in the /WEB-INF/lib folder which participates in the webapp's runtime classpath. Just copy the JAR file straight in the directory /WEB-INF/lib and rebuild/redeploy/restart.
In addition, I assume that you are using a Java Application Server (as you are creating Servlets). Therefore, I would consider using a JDBC Connection Pool as an alternative.

Run a java webservice on a server

I have a Java Webservice code . Currently I am running it on a localhost. What changes should be made when I run this on another server(with static IP).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
public class RetailerWS {
public String customerData(){
String customerInfo = "";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/retailer","root","chathura");
//Find customer information where the customer ID is maximum
PreparedStatement statement = con.prepareStatement("SELECT * FROM customers WHERE C_ID = (SELECT MAX(C_ID) FROM customers)");
ResultSet result = statement.executeQuery();
while(result.next()){
customerInfo = customerInfo + result.getString("name") + "&" + result.getString("C_ID") + "&"+result.getString("address") + "&"+result.getString("email");
//Here "&"s are added to the return string. This is help to split the string in Android application
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return customerInfo;
}
}
You need not to make any change if database is also hosted on the same server. If DB is on other server then change this line :
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/retailer","root","chathura");
to have the ip/address or hostname of your DB server.
Your web service clients need to use the address of you new server where you are hosting the web service, to call its methods.

Categories