Java desktop app with thesql database

databasejavaMySQLsoftware-distribution

I'm currently in the process of learning Java and swing and in doing so am trying to create a desktop app.

As part of this app I have set up a mysql database which the app is connected to, however I'm uncertain as to how this would work if I was to distribute the app for other users, how would I create a database that they are able to use on their system if they don't have mySQL installed or the database initiated.

Best Answer

As pvg has mentioned, a good option to use is an embedded database. The reason here is that the database can be included as a single JAR file, rather than needing to be installed on the system's user. Usually, you can access the databases using the standard JDBC API, so it really can act as a replacement for your current MySQL DB. The library will manage creation of DB files so you don't have to install anything.

Of course, these options are typically less robust than something like Oracle, however, it may suit your needs just fine.

For example, I recently utilized the H2 database, a 100% Java embedded DB, in a project of mine. http://www.h2database.com/html/main.html

Here is some example code which shows how using something like H2 would differ than MySQL when you want to get a connection object, but note, interacting with the DB to run queries would be the same as with MySQL:

import org.h2.jdbcx.JdbcDataSource;
import java.sql.*;

/**
 * Sets and returns a DB connection, if not already done
 */
private static Connection getDBConnection() {
    if (mDBConnection != null)
        return mDBConnection;

    Connection conn = null;
    try {
        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL("jdbc:h2:C:/MyDBDirectory/");
        conn = ds.getConnection();
    } catch (SQLException e) {
        mLogger.severe("Error opening DB connection or creating tables: " + e.getMessage());
    }
    mDBConnection = conn;
    return mDBConnection;
}
Related Topic