Access Denied? Wrong user / pass - java

I'm trying to write a java program to connect to the same MySQL database my website uses. I am using the same login details, minus the hostname ofcourse, but I am getting these errors:
SQLException: Access denied for user 'USER'#'HOSTNAME' (using password: YES)
SQLState: 28000
VendorError: 1045
I am using the hostname my host provided, and the password and user are the same details I have on my website.
Here is the code snippit:
public main() {
Connection con = null;
String mysql_hostname = "HOST";
String mysql_username = "USER";
String mysql_password = "PASS";
String mysql_database = "DB";
int mysql_port = 3306;
initComponents();
try {
con = DriverManager.getConnection("jdbc:mysql://"+ mysql_hostname +":"+ mysql_port +"/"+ mysql_database +"?user="+ mysql_username +"&password="+ mysql_password);
}
catch(SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
This is probably to do with some cPanel settings, but I am very new to Java, so asking couldn't hurt...right? :D

On cPanel as I remember when you create a db user there is also a hostname associated with that user default (localhost), If you are running your code on local machine you have to add your IP (public IP) or % in hostname for this db user from cPanel. So mysql will allow connection from your machine.
Note: adding % is risky, make sure you have a strong password.

Related

Issues with username and password when connecting to oracle database 12c through ojdbc

I have SQL developer installed and a properly configured DB, I create a user from sys like so:
CREATE USER random IDENTIFIED BY 12345;
GRANT ALL PRIVILEGES TO random;
I attempt to connect to the oracle SQL database with the ojdbc8.jar found in oracles website like this:
String url = "jdbc:oracle:thin:random/12345#localhost:1521:home";
try{
Connection dbConn = DriverManager.getConnection(url);
}catch(Exception e){
System.out.println("Exception: " + e.getLocalizedMessage());
}
However I receive this error:
Exception: ORA-01017: invalid username/password; logon denied
The last time I asked this question it was just populated by answers that have no actual answer to the problem at hand, I don't need to change the driver to a different one, I don't need to instantiate some sort of factory nonsense that just adds complexity, all I want to know is how I'm meant to connect to an account that is part of my DB so I can perform basic SQL functions.
Edit:
It just occurred to me that it is a pdb, is there a modification needed to the connection url that anyone can point out?
Try:
Connection dbConn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:home", "random", "12345");
PDB connections need a slight tweak.
Please use localhost:port/sid instead of localhost:port:sid:
if (isPluggableDB) {
conn = DriverManager.getConnection("jdbc:oracle:thin:#" + hostName + ":" + hostPort + "/" + sid, userName, password);
} else {
conn = DriverManager.getConnection("jdbc:oracle:thin:#" + hostName + ":" + hostPort + ":" + sid, userName, password);
}

AWS Lambda connecting to publicly accessible AWS RDS

I created a publicly accessible PostgreSQL RDS in AWS and have the following code to connect to it:
try {
DriverManager.registerDriver(new org.postgresql.Driver());
String url = "jdbc:postgresql://" + DATABASE_SERVER_NAME + ":" + DATABASE_PORT_NUMBER + "/" + DATABASE_NAME + "?user=" + DATABASE_USER + "&password=" + DATABASE_PASSWORD;
try (Connection connection = DriverManager.getConnection(url)) {
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM \"" + PHANTOM_LOAD_STORE_DATABASE_TABLE_NAME + "\"")) {
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
System.out.println(resultSet.getString("userid"));
}
}
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
When this is run locally it connects to the database server successfully.
When this is run in an AWS Lambda it fails to connect with the following error:
org.postgresql.util.PSQLException: The connection attempt failed.
...
Caused by: java.net.SocketTimeoutException: connect timed out
The lambda is not in a VPC and has the role policy arn:aws:iam::aws:policy/AmazonRDSDataFullAccess.
Can someone tell me what I'm doing wrong?
Despite creating the RDS database to be publicly accessible it had a security group rule that only allowed incoming requests from my IP (the one that created the database). Editing its security group's incoming rules to allow requests from anywhere has allowed the lambda to connect to the database.
The policy arn:aws:iam::aws:policy/AmazonRDSDataFullAccess seems unnecessary.
Thanks to this answer for helping me work it out.

"Could not create connection to database server" netbeans google cloud sql error

I am trying to create my first API using java httpServlet and netbeans which will be connected to a database on google cloud based its examples and documentations. I have not created the database, but I was given the necessary credentials and vars to create the connection. So I have downloaded the project from github, and when I tried to open it from netbeans there was some issues concerning dependencies ... So I resolved them, I replaced the credentials with their values and run the project; Unfortunately an error was thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. I made some searches but did not get any result... Could it be an error from this code ? an error from database security if it was invisible on cloud? Any help is more than appreciated.
public class ListTables {
public static void main(String[] args) throws IOException, SQLException {
String instanceConnectionName = "<foo:foo:bar>";
String databaseName = "myDatabaseName ";
String username = "myUsername ";
String password = "<myPass>";
if (instanceConnectionName.equals("<insert_connection_name>")) {
System.err.println("Please update the sample to specify the instance connection name.");
System.exit(1);
}
if (password.equals("<insert_password>")) {
System.err.println("Please update the sample to specify the mysql password.");
System.exit(1);
}
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
databaseName,
instanceConnectionName);
try{
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
/* try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("select * from wf_accounts;");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}*/
}catch(Exception ex){
System.out.println("Error: " + ex.toString());
}
Update
Same error was thrown when I did this:
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
"",
"");
Any hints?
First you have to check whether the mysql server is running on.If you are Windows user you can simply
Go to Task Manager
Go to Services
then search for your Mysql server(eg:for my case its MYSQL56)
then you will see under the status column it says its not running
by right clicking and select start
If it's already running then you have to do as in mysql Documentation,
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem

Java Connection String to Oracle Cloud Database

I had problem when connecting to Oracle Cloud Database from java code.
I have no problem connecting other non-cloud oracle databases.
I can connect to the Oracle Cloud Database with sql tools, except from the java codes.
The hostname, username and password is correct one, i don't reveal the real username and password.
Error: java.sql.SQLException:
SQLException: SQLState(null) vendor code(17002)
java.sql.SQLException: Io exception: Oracle Error ORA-12650: No common encryption or data integrity algorithm
My code as following:
String dbURL = "jdbc:oracle:thin:#192.133.133.23:1521:ORCL";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(dbURL, "username1", "password");
}catch(Exception)
{
e.printStacktrace();
}
/**
* The below one is for oracle thin client
Its worked for the ojdbc6 driver.
*/
public Connection conCheck() {
Connection con=null;
try { //step1 load the driver class
Class.forName("oracle.jdbc.OracleDriver");
Properties props = new Properties();
props.put("oracle.net.encryption_client", "REQUIRED");
props.put("oracle.net.encryption_types_client", "( " + AnoServices.ENCRYPTION_AES256 + "," +AnoServices.ENCRYPTION_AES192 + ")");
props.put("oracle.net.crypto_checksum_types_client", "( SHA1 )");
props.put("user", "username");
props.put("password","password");
//step2 create the connection object
con=DriverManager.getConnection( "jdbc:oracle:thin:#host:port:serveiceid",props);
System.out.println("Con"+con);
}catch(Exception e) {e.printStackTrace(); }
return con;
}
Seems like changing syntax in your connection string to lookup SERVICE_NAME instead of SID must help you connect your database.
String dbURL = "jdbc:oracle:thin:#192.133.133.23:1521/ORCL";
Additional Read : Thin-style Service Name Syntax
If this as well doesn't help, then would suggest to add below 2 lines to your sqlnet.ora in database.
SQLNET.CRYPTO_CHECKSUM_TYPES_CLIENT= (SHA1)
SQLNET.CRYPTO_CHECKSUM_CLIENT = requested
First mandatory check is to verify the oracle jdbc version. if you use incompatible version,we will get this kid of errors.

Connecting to sybase using jdbc in solaris

I am trying to learn how to use jdbc.
Normally to connect to sybase db on solaris I use:
isql -Usa -Pxxxxxx -Dxxxxxx
its gets connected to the db by the above.and i can rightaway execute the queries.
Now i am trying to just do a similar thing using java.
below is my code.
public class SKRSample
{
public static void main(String args[])
{
try
{
Class.forName("com.sybase.jdbc.SybDriver");
}
catch (ClassNotFoundException cnfe)
{
System.err.println("Error loading driver: " + cnfe);
}
try
{
String host = "172.16.65.33";
String dbName = "bsmdb";
int port = 1234;
String url = "jdbc:sybase:Tds:" + host + ":" + port + ":" + "?SERVICENAME=" + dbName;
for (int n = 0; n<args.length; n++) {
if (args[n].equals("-u")) user = args[++n];
else if (args[n].equals("-p")) password = args[++n];
else throw new IllegalArgumentException("Unknown argument.");
}
Connection con = DriverManager.getConnection(url, user, password);//here is the error.
The last line of the code is where there is a runtime error.
i compiled the code and execueted as below:
setenv LOGIN "sa"
setenv PASSWORD "xxxxxxx"
javac SKRSample.java
java SKRSample -u $LOGIN -p $PASSWORD
the error i am getting is :
Unexpected exception : java.sql.SQLException: No suitable driver found for jdbc:sybase:Tds:172.16.65.33:1234:?SERVICENAME=bsmdb, sqlstate = 08001
i have a doubt that either the host is incorrect or the port is incorrect or the url i am framing is incorrect.how can get the host name if at all it is incorrect.and also how can get the port number if the problem lies there.
But i am not sure about the problem.Can anyone give me some head's up regarding where exactly the problem is there.
Seems that the JDBC url format is wrong.
the right format is jdbc:jtds:sybase://<host>[:<port>][/<database_name>]
You will have to download the driver and execute the class so that it uses the driver in the path specified by you.
You need to use proper JDBC driver and connection string together. For example, you can use "com.sybase.jdbc2.jdbc.SybDriver" (in jconn2.jar) and "jdbc:sybase:Tds:MyDbComputerNameOrIP:2638" together. Please check the following page for more options.
Sybase JDBC Driver and URL Information
In your code, it seems that you added extra ":" in the connection URL. Remote the ":" after port number. The following two connection URL should work with "com.sybase.jdbc.SybDriver".
String url = "jdbc:sybase:Tds:" + host + ":" + port + "?SERVICENAME=" + dbName;
or
String url = "jdbc:sybase:Tds:" + host + ":" + port + "/" + dbName;
Class.forName("net.sourceforge.jtds.jdbc.Driver");
And use JTDS driver jar in the classpath
It may be a bit late, but still I had the same issue and spent much time investigating, so I'll put some outcome here:
1. We need to include the driver class in our code as well as java.sql:
import com.sybase.jdbc3.jdbc.SybDriver;
import java.sql.*;
2. We need to run javac with the path to the driver in the classpath (I have jconn3.jar here - /usr/local/localagent/jar/jconn3.jar):
javac -cp "/usr/local/localagent/jar/*" test_conn.java
3. We need to put the same classpath when running the class:
java -cp ".:/usr/local/localagent/jar/*" test_conn
My code for test_conn.java is below:
import com.sybase.jdbc3.jdbc.SybDriver;
import java.sql.*;
public class test_conn {
public static void main(String[] args) {
String host = "myhost";
String url = "jdbc:sybase:Tds:"+host+":4100";
String username = "username";
String password ="password";
String dbname ="dbname";
SybDriver sybDriver = null;
Connection conn;
try
{
sybDriver=(SybDriver)Class.forName("com.sybase.jdbc3.jdbc.SybDriver").newInstance();
System.out.println("Driver Loaded");
conn = DriverManager.getConnection( "jdbc:sybase:Tds:"+host+":4100?SERVICENAME="+dbname, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("sp_helpdb");
rs.next();
System.out.println(rs.getString(1));
conn.close();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
It worked for me, so I hope this helps.

Categories

Resources