Cannot connect to OpenShift mysql remotely with jdbc - java

I am trying to connect to a remote database on openshift using jdbc.
Here is my code below -
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
public class Conn {
public static String url = "jdbc:mysql://127.9.77.2:3306/mysql";
public static String user = "adminSKr7Tbz";
public static String password = "h1xha****";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// TODO Auto-generated method stub
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println("Connecting to database...");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from country LIMIT 10;");
while (rs.next()) {
HashMap map = new HashMap();
String name = rs.getString("Name");
Integer col = Integer.parseInt(rs.getString("Area"));
map.put("name",name);
map.put("value",col);
System.out.println(map);
}
}
}
I get the following error -
Exception in thread "main" java.sql.SQLException: Access denied for user 'adminSKr7Tbz'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3808)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1256)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at visualize.Conn.main(Conn.java:18)
Can anyone please help me fix this.
I am giving all credentials correctly , even then it says Access Denied.

It is possible that MySQL is only setup to accept connections on local host. Can you update the grant statement to use 'user#%'

String USERNAME = System.getEnv("OPENSHIFT_MYSQL_DB_USERNAME");
String PASSWORD = System.getEnv("OPENSHIFT_MYSQL_DB_PASSWORD");
String DB_NAME = System.getEnv("OPENSHIFT_APP_NAME");
String FORNAME_URL = "com.mysql.jdbc.Driver";
String URL = "jdbc:"+System.getEnv("OPENSHIFT_MYSQL_DB_URL")+ DB_NAME;
Connection m_connection = DriverManager.getConnection(URL , USERNAME , PASSWORD);
Use it like this.Openshift will not relay on static ip so they will not accept your connection via that ip or the localhost. Also if you are trying it on your local server rather that deploying it on openshift you have to use ssh tokens for the connection and i think it's not allowed.

Related

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.

Login failed for user 'DESKTOP-6U7R1AC\Amit'

I want to connect my sql server database with java. here is the code I have
package myPackage;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
String url = "jdbc:sqlserver://DESKTOP-6U7R1AC\\SQLEXPRESS;databaseName=sample1;";
String uname="DESKTOP-6U7R1AC\\Amit";
String pass="";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url,uname,pass);
System.out.println("command completed sucessfully");
Statement stmt =(Statement) conn.createStatement();
String query ="SELECT * FROM tblPerson";
ResultSet rs =((java.sql.Statement) stmt).executeQuery(query);
while(rs.next()){
System.out.println(rs.getInt(1) +" "+rs.getString(2) +" "+rs.getString(3) );
}
}
}
Please note that
I am using Microsoft SQL server management studio 18.
I have added the mssql-jdbc-8.4.1.jar in the build path.
my SQL server details
server type: Database Engine
server name: DESKTOP-6U7R1AC\SQLEXPRESS
Authentication: Windows Authentication
User name: DESKTOP-6U7R1AC\Amit
Password:
I am getting the following error-
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'DESKTOP-6U7R1AC\Amit'. ClientConnectionId:497452a3-a4f3-40a8-b68e-864e269ad66a
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:283)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:129)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:37)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:5233)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3988)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:85)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3932)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7375)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:3206)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2713)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2362)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2213)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1276)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:861)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at myPackage.Test1.main(Test1.java:22)
The problem is solved now. here is the correct code for...
package myPackage;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
String url = "jdbc:sqlserver://DESKTOP-6U7R1AC\\SQLEXPRESS;databaseName=sample1;integratedSecurity=true";
String uname="DESKTOP-6U7R1AC\\Amit";
String pass="";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url,uname,pass);
System.out.println("command completed sucessfully");
Statement stmt = conn.createStatement();
String query ="SELECT * FROM tblPerson";
ResultSet rs =((java.sql.Statement) stmt).executeQuery(query);
while(rs.next()){
System.out.println(rs.getInt(1) +" "+rs.getString(2) +" "+rs.getString(3) );
}
}
}
The changes I did.
fist set the integratedSecurity=true and then I was getting an error saying that sqljdbc_auth.dll is not found in java.library.path . Then I added the sqljdbc_auth.dll in java.library.path and it worked.

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.

Categories