Establishes a connection to the MYSQL SQL database and returns that newly made connection. - Android Database

Android examples for Database:Database Connection

Description

Establishes a connection to the MYSQL SQL database and returns that newly made connection.

Demo Code


//package com.book2s;
import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.SQLException;

public class Main {
    /**/*w w w . ja va  2  s . c  om*/
     * Establishes a connection to the SQL database and returns that newly made
     * connection. I followed this guide to understand how to connect to the
     * MySQL database that is created when making a new Amazon Elastic
     * Beanstalk application:
     * http://docs.amazonwebservices.com/elasticbeanstalk/latest/dg/create_deploy_Java.rds.html
     * A MySQL JDBC Driver is required for this MySQL connection to actually
     * work. You can download that driver from here:
     * https://dev.mysql.com/downloads/connector/j/
     * 
     * @return
     * Returns a newly made connection to the SQL database.
     * 
     * @throws SQLException
     * If a connection to the SQL database could not be created then a
     * SQLException will be thrown.
     * 
     * @throws Exception
     * If, when trying to load the MySQL JDBC driver there is an error, then
     * an Exception will be thrown.
     */
    public static Connection acquireSQLConnection() throws SQLException,
            Exception {
        // ensure that the MySQL JDBC Driver has been loaded
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        // acquire database credentials from Amazon Web Services
        final String hostname = System.getProperty("RDS_HOSTNAME");
        final String port = System.getProperty("RDS_PORT");
        final String dbName = System.getProperty("RDS_DB_NAME");
        final String username = System.getProperty("RDS_USERNAME");
        final String password = System.getProperty("RDS_PASSWORD");

        // create the connection string
        final String connectionString = "jdbc:mysql://" + hostname + ":"
                + port + "/" + dbName + "?user=" + username + "&password="
                + password;

        // return a new connection to the database
        return DriverManager.getConnection(connectionString);
    }
}

Related Tutorials