3

I have instances of amazon ec2 and rds which both run in a virtual private cloud. The rds contains a mysql database. I am able to connect to the rds database with mysql workbench by inputting the database information(host, port#, database, user) and also the ssh details for the ec2 instance(host, port#, user, keyfile).

I am now writing a java program that needs to access the database. I am confused as to how this can be done with the JDBC(java database connection) library. There are examples online regarding the use of JDBC, however they don't seem to be addressing certain issues I am facing.

For example, to connect to my database I must also ssh into the ec2 instance. Secondly my ec2 instance uses a key file rather than a password and I have not seen any examples of how to implement this in code.

I would really appreciate any advice or code example pertaining to this issue. Please let me know if I need to clarify anything. Thanks

2 Answers 2

4

If you can connect with MySQL Workbench you pretty much got everything set up. This mean your security group is open and you are ready to connect remotely. You don't need to SSH into your EC2 server. You just need your public ip or DNS (host), the port you are using and your database username and password. Then, you just need to do something like the following code.

Class.forName("com.mysql.jdbc.Driver");  
Connection conn = DriverManager.getConnection(  
"jdbc:mysql://{public dns or ip}:{port}/{database name}","{username}","{password}");
Statement stmt = conn.createStatement();  
ResultSet rs = stmt.executeQuery("select * from table");

This should be enough to connect you to your DB. Of course, change the {} with their respective value. If you need more information, you can check out this page.

Sign up to request clarification or add additional context in comments.

Comments

0

If you are running your Java Program on the EC2 instance which is part fo the VPC and security group settings allows connection on the RDS port, all you need to do is create a new connection class with the RDS server configuration (RDS IP address, Port no, DB User and DB password).

If your Java Program is running on a server outside VPC, you will need to manage the VPC network and security group to allow the remote connection form outside VPC.

You can refer the AWS documentation for step by step process to manage RDS in VPC.

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.Scenarios.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.