AWS Lambda connecting to publicly accessible AWS RDS - java

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.

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);
}

"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 With Microsoft Access Database

I'm trying to use Ucanaccess library with java to connect to Microsoft Access ...
So i tried executing this code and it worked ....
String url = "jdbc:ucanaccess:\\C:/Access.ACCDB";
String query = "select * from [Donations]";
try
{
java.sql.Connection con =DriverManager.getConnection(url, "","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
System.out.println("Account No: " + rs.getString(1));
System.out.println("Surname: " + rs.getString(2));
System.out.println("First Name: " + rs.getString(3));
}
}
catch(SQLException ex)
{
while (ex!=null)
{
System.out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException();
}
}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
let me explain what i'm trying to do
I have a Asp.Net website that uses Microsoft Access Database and in the same time i need a server (Java Application) to access the same Database (Microsoft Access) but when i uploaded the Database online to test if the server can get to the Database and modified the String for the connection ....
here is what it looked like
String url = "jdbc:ucanaccess://www.filetolink.com/download/?h=eaa4aab688d25e270539868d712961ab&t=1467140283&f=3ca9ad1869;";
String query = "select * from [Donations]";
try
{
java.sql.Connection con =DriverManager.getConnection(url, "","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
System.out.println("Account No: " + rs.getString(1));
System.out.println("Surname: " + rs.getString(2));
System.out.println("First Name: " + rs.getString(3));
}
}
catch(SQLException ex)
{
while (ex!=null)
{
System.out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException();
}
}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
I tried running the code but I had an error message ... Here it is :
SQL Exception: UCAExc:::3.0.6 given file does not exist:
http:\www.filetolink.com\download\?h=e6dc57e3485defa7c53e1c968a87fb1f&t=1467139906&f=3ca9ad1869
So What i'm asking for is :
1.How can I publish the website with the access database and let both of the Server and the website access the Database ?? (The server and the website aren't on the same Machine or computer .... )
2.if the answer to my question is that i can't ... then what can i do ?? other suggestions ? for having Database that can be accessed by a Remote Server (Java Application ) and A website (Asp.Net)
MS Access is a desktop database not a server database management system. If a program wants to access to such a database, the database file has to be on a local or network filesystem. So if your two applications are running on different machines in the same intranet, putting the database file on network filesystem would be a solution.
BUT: MS Access was never meant to be used as a web application's backend database. You should use a real server database like MS SQL Server, PostgreSQL or MySQL instead. Then your applications can access the database via network protocol. Theoretically it is possible to open the database port to the internet so that you can connect from everywhere. But this is not recommended due to security reasons.
So if your two applications aren't running in the same intranet it is better to create some webservices and let your other program call these webservices to get the needed information.

Access Denied? Wrong user / pass

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.

errors while try to run executeQuery/prepared statements()

SQL statement is not executedcom.mysql.jdbc.CommunicationsException: Communications link >failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException MESSAGE:
Connection refused
STACKTRACE:
java.net.ConnectException: Connection
refused at
java.net.PlainSocketImpl.socketConnect(Native
Method) at
java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:310)
at
java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:176)
at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:163)
at
java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at
java.net.Socket.connect(Socket.java:546)
at
java.net.Socket.connect(Socket.java:495)
at
java.net.Socket.(Socket.java:392)
at
java.net.Socket.(Socket.java:235)
at
com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at
com.mysql.jdbc.MysqlIO.(MysqlIO.java:271)
at
com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at
com.mysql.jdbc.Connection.(Connection.java:1555)
at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at
java.sql.DriverManager.getConnection(DriverManager.java:620)
at
java.sql.DriverManager.getConnection(DriverManager.java:200)
at
org.jtdemo.preparedst.main(preparedst.java:18)
** END NESTED EXCEPTION **
Last packet sent to the server was 1
ms ago. at
com.mysql.jdbc.Connection.createNewIO(Connection.java:2847)
at
com.mysql.jdbc.Connection.(Connection.java:1555)
at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at
java.sql.DriverManager.getConnection(DriverManager.java:620)
at
java.sql.DriverManager.getConnection(DriverManager.java:200)
at
org.jtdemo.preparedst.main(preparedst.java:18)
My program is
package org.jtdemo;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class preparedst
{
//private static final String y = null;
public static void main(String arg[])throws Exception
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3036/mylib_db";
Connection con=DriverManager.getConnection(url,"nikki","dkm007");
String query = " select c.sub_category, b.title,b.author,b.b_key,ta.available_copies" +
"from Book_dim b,Category_list c,item_availablity_fact ta" +
" where sub_category = 'Mathematics' and " +
" c.category_id=b.category_id and " +
" b.b_key=ta.b_key " ;
/*ps = con.prepareStatement(" select c.sub_category, b.title,b.author,b.b_key,ta.available_copies" +
"from Book_dim b,Category_list c,item_availablity_fact ta" +
" where sub_category = ? and " +
" c.category_id=b.category_id and " +
" b.b_key=ta.b_key ");*///pass sql query ,no parameter passing
//ps.String(1, "Mathematics"); // set input parameter
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query) ;
while(rs.next())
{
String scat = rs.getString(1);
String ttl = rs.getString(2);
String auth = rs.getString(3);
int bkey = rs.getInt(4);
int avcop = rs.getInt(5);
//String b_key;
System.out.println("subcategory:"+scat+"title:"+ttl+"author:"+auth+"bookkey:"+bkey+"availcopies:"+avcop);
}
con.close();
//ps.close();
}
catch(Exception e)
{
System.out.println("SQL statement is not executed");
e.printStackTrace();
}
}
}
i am using jdk 1.6,mysql-connector-java-5.0.8-bin.jar,Eclipse Version: 3.5.2.
Please help.................
The exception tells you the problem. If your connection was refused, then there is something wrong with either the configuration of the client or the server. So the first thing to check is the JDBC URL. You need to verify the following:
The server is at localhost
The server is serving on port 3036 (the default port for MySQL is 3306, so this may be your problem)
You have a database on that server named 'mylib_db'
Your user name is correct
Your password is correct (in the future you may want to use placeholder text like 'password')
If all that information is correct, you need to examine your server to ensure that 'nikki' has permission to connect to the database over the network.
It looks like a network problem. It seems the database is not listening on the port you're telling java to connect to.
I would check that the port is indeed listening (via netstat), check any anti-virus, firewall, security programs, etc. If this all comes back good then perhaps a restart of your database program (myssql) would do the trick.

Categories

Resources