Connecting to MySQL via Java

The Web server ozark is also configured as a database server using MySQL. You can write Java programs to access it using Java's database API, called JDBC. As an example of how to use JDBC as it's installed here, we'll use the ListStates program listed at the bottom of this page.

Note that MySQL is configured to allow connections only from within the Linux network.

An example JDBC program

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;

public class ListStates {
    /* DataBase account info for MySQL */
    private static final String URL = "jdbc:mysql://ozark";
    private static final String DATABASE = "census";
    private static final String USERNAME = "jdbc";
    private static final String PASSWORD = "warriors";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch(ClassNotFoundException e) {
            System.err.println("Exception in static initializer:");
            e.printStackTrace();
        }
    }

    private static ResultSet execSql(String cmd) {
        try {
            Connection conn = DriverManager.getConnection(URL
                + "/" + DATABASE, USERNAME, PASSWORD);
            Statement stat = conn.createStatement();
            boolean hasResultSet = stat.execute(cmd);
            if(hasResultSet) {
                return stat.getResultSet();
            }
        } catch(SQLException e) {
            System.err.println("Exception in execSql:");
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        try {
            ResultSet results = execSql("SELECT name FROM States");
            if(results != null) {
                while(results.next()) {
                    System.out.println(results.getString(1));
                }
            }
        } catch(SQLException e) {
            System.err.println("Exception in main:");
            e.printStackTrace();
        }
    }
}