简体   繁体   中英

JDBC connecting to MySQL on Amazon ec2

I'm a little new at that, but after starting my ec2 instance, and installing MySQL instance through RDS, I manage to connect to it through MySQL Workbench using ssh (.pem file).

My problem is I can't seem to have it right, when I'm trying to connect with jdbc, how exactly the authentication suppose to be done?

Here is my code, hope somebody can give me a hint on how to proceed:

public void create_table(){
    Connection c = null;
    Statement stmt = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");

//          c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");





      System.out.println("Opened database successfully");

      stmt = c.createStatement();
      String sql = "CREATE TABLE USERS " +
                   "(ID INT PRIMARY KEY   ," +
                   " DEVICE           TEXT    NOT NULL, " + 
                   " NAME            TEXT     NOT NULL)"; 
      stmt.executeUpdate(sql);
      stmt.close();
      c.close();
    } catch ( Exception e ) {
          System.err.println( e.getClass().getName() + ": " + e.getMessage() );
          System.exit(0);
    }

EDIT

I forgot few important details...

  1. I wrote my code in Java using Jersey and servelt.
  2. I Uploaded my WAR file to my ec2 instance.

Now after both web-app and MySQL server are running on the same instance, I want to build the communication..

Thank you!

Your SQL Syntax is incorrect. Text values are inserted as VARCHAR type in SQL . You can change the length of the text value depending on your need by changing the value with in the bracktes in VARCHAR(HERE) . Try this code.

   //STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";

   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");

      //STEP 4: Execute a query
      System.out.println("Creating table in given database...");
      stmt = conn.createStatement();

      String sql = "CREATE TABLE USERS " +
               "(ID INTEGER not NULL," +
               " DEVICE VARCHAR(255) not NULL," + 
               " NAME VARCHAR(255) not NULL,"+
               "PRIMARY KEY (ID))"; 

      stmt.executeUpdate(sql);
      System.out.println("Created table in given database...");
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample

how exactly the authentication suppose to be done?

you can use one of the form you use in your example but there are wrong things in both

c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");

you connect to localhost, if you have your test db on RDS you need to reference the end point of RDS like your second example

c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");

Here the end point will be correct but the string to connect is wrong. You can use the following form

String jdbcUrl = "jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test?user=root&passwor‌​d=password"; 
Connection con = DriverManager.getConnection(jdbcUrl); 

or

String url = "jdbc:mysql://mydatabase.test.us-east-1.rds.amazonaws.com:3306/";
String userName = "root";
String password = "password";
String dbName = "test";
Connection connection = DriverManager.getConnection(url + dbName, userName, password);

To find precisely your database end-point, login to the RDS console (make sure to select the right region if not us-east-1), select your database and the Endpoint will be there

在此处输入图片说明

The other potential issue you might run is on Security Groups

The DB instance was created using a security group that does not authorize connections from the device or Amazon EC2 instance where the MySQL application or utility is running. If the DB instance was created in a VPC, it must have a VPC security group that authorizes the connections. If the DB instance was created outside of a VPC, it must have a DB security group that authorizes the connections.

Check your security group rules for both the RDS DB and the ec2 instance and make sure you can connect that the ec2 instance has access to RDS server

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM