Ads

Get STM32 tutorial using HAL at $10 for a limited time!

Saturday, May 2, 2015

Java and PosgreSQL Tutorial 1 - Database Connection

In this tutorial I will share how to make an application with Java that use PostgreSQL database. I will use Netbeans IDE for this tutorial. Netbeans already has PostgreSQL library, so to use this library you can add to your project from Library folder (right click) then select Add Library. In the Add Library dialog, select PostgreSQL JDBC Driver.


For this tutorial, I will share how to make connection between the application and the database. I will make a class called DatabaseHelper. This class is responsible for handling database functions such as database connection, INSERT, UPDATE, DELETE, SELECT and so on. The database that I used for this tutorial is consist of one table called tb_music. This table is consist of three columns (id, title, and artist).


To make a connection you need 5 parameters (host name, port, database name, username, and password). I made these 5 parameters as a constant variable.
// Database connection settings.
private final String HOST_NAME = "localhost";
private final String PORT = "5432";
private final String DATABASE_NAME = "db_test_java";
private final String USERNAME = "postgres";
private final String PASSWORD = "root";
The next step is to make PostgreSQL connection object called mConnection.
private Connection mConnection;
The last step is to make 2 method, the first method is for open database connection and the second is for close database connection.
// Open database connection.
public void openConnection() {
    try {
        mConnection = DriverManager.getConnection(
                "jdbc:postgresql://" + HOST_NAME
                + ":" + PORT
                + "/" + DATABASE_NAME,
                USERNAME, PASSWORD);
    } catch (SQLException e) {
        showError("openConnection(): " + e.toString());
    }
}

// Close database connection.
private void closeConnection() {
    try {
        mConnection.close();
    } catch (SQLException e) {
        showError("closeConnection(): " + e.toString());
    }
}
In the catch block there is a function called showError(), that function is for showing the error message to message dialog. This is the showError() function.
// Show error to message dialog.
private void showError(String message) {
    JOptionPane.showMessageDialog(null,
            "<html><body><p style='width: 200px;'>"
            + message
            + "</p></body></html>", 
            "Error", JOptionPane.ERROR_MESSAGE);
}
In this message dialog, I use html tag to wrap the message width to 200px.

No comments :

Post a Comment