How To Embed Mysql Database Into Java Application

31-08-2014

Embedding mysql into java application is not straightforward. Therefore, I will try to explain necessary operations step by step.

1. Download this library file then extract jar files into a folder.
2. Create a Java application and add downloaded jar files into the application lib folder

If you use maven application add following dependencies into pom.xml file

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-mxj-gpl</artifactId>
    <version>5.0.12</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-mxj-gpl-db-files</artifactId>
    <version>5.0.12</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.32</version>
</dependency>

Note: Above dependencies can be found in maven central repository, but I strongly suggest that use these downloaded jar files by installing them locally by using following mvn commands:
mvn install:install-file -Dfile=mysql-connector-mxj-gpl-db-files-5.0.12.jar ^
 -DgroupId=mysql -DartifactId=mysql-connector-mxj-gpl-db-files -Dversion=5.0.12 -Dpackaging=jar
 
mvn install:install-file -Dfile=mysql-connector-java-5.1.32.jar ^ 
-DgroupId=mysql -DartifactId=mysql-connector-java -Dversion=5.1.32 -Dpackaging=jar
 
mvn install:install-file -Dfile=mysql-connector-mxj-gpl-5.0.12.jar ^
 -DgroupId=mysql -DartifactId=mysql-connector-mxj-gpl -Dversion=5.0.12 -Dpackaging=jar

3. After step 1 and step create a class named as ConnectorMXJObjectTestExample.java and add following codes:
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.Map;
import com.mysql.management.MysqldResource;
import com.mysql.management.MysqldResourceI;
import com.mysql.management.util.QueryUtil;
public class ConnectorMXJObjectTestExample {
    public static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
    public static void main(String[] args) throws Exception {
        File ourAppDir = new File(System.getProperty(JAVA_IO_TMPDIR));
        File databaseDir = new File(ourAppDir, "mysql-mxj");
        int portNumber = Integer.parseInt(System.getProperty("c-mxj_test_port",
                "3336"));
        String userName = "olyanren";
        String password = "1987";
        MysqldResource mysqldResource = startDatabase(databaseDir, portNumber,
                userName, password);
        Class.forName(DRIVER);
        Connection conn = null;
        try {
            String dbName = "our_test_app";
            String url = "jdbc:mysql://localhost:" + portNumber + "/" + dbName
                    + "?" + "createDatabaseIfNotExist=true"
                    ;
            conn = DriverManager.getConnection(url, userName, password);
            String sql = "SELECT VERSION()";
            String queryForString = new QueryUtil(conn).queryForString(sql);
           
            System.out.println("------------------------");
            System.out.println(sql);
            System.out.println("------------------------");
            System.out.println(queryForString);
            System.out.println("------------------------");
            System.out.flush();
            Thread.sleep(100); // wait for System.out to finish flush
        } finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                mysqldResource.shutdown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static MysqldResource startDatabase(File databaseDir, int port, String userName, String password) {
        MysqldResource mysqldResource = new MysqldResource(databaseDir);
        Map database_options = new HashMap();
        database_options.put(MysqldResourceI.PORT, Integer.toString(port));
        database_options.put(MysqldResourceI.INITIALIZE_USER, "true");
        database_options.put(MysqldResourceI.INITIALIZE_USER_NAME, userName);
        database_options.put(MysqldResourceI.INITIALIZE_PASSWORD, password);
 
        mysqldResource.start("test-mysqld-thread", database_options);
        if (!mysqldResource.isRunning()) {
            throw new RuntimeException("MySQL did not start.");
        }
        System.out.println("MySQL is running.");
        return mysqldResource;
    }
}

If you see the following error, then you have to override platform-map.properties file located in mysql-connector-mxj-gpl-db-files-5.0.12.jar
Exception in thread "main" java.util.MissingResourceException: Resource '5-5-9/Windows_8-x86/mysqld.exe' not found

New platform-map.properties file:
#String key = System.getProperty("os.name") + "-" + System.getProperty("os.arch");
#key = key.replace(' ', '_').replace('/', '_').replace('\\', '_');
 
Linux-i386=Linux-i386
Linux-x86=Linux-i386
Linux-i686=Linux-i386
Linux-x86_64=Linux-i386
Linux-amd64=Linux-i386
Linux-ia64=Linux-i386
 
Mac_OS_X-i386=Mac_OS_X-i386
Mac_OS_X-x86_64=Mac_OS_X-i386
 
SunOS-sparc=SunOS-sparc
Solaris-sparc=SunOS-sparc
SunOS-sparcv9=SunOS-sparc
SunOS-x86=SunOS-x86
Solaris-x86=SunOS-x86
SunOS-amd64=SunOS-x86
 
FreeBSD-x86=FreeBSD-x86
FreeBSD-i386=FreeBSD-x86
 
Windows_7-x86=Win-x86
Windows_Vista-x86=Win-x86
Windows_2003-x86=Win-x86
Windows_XP-x86=Win-x86
Windows_2000-x86=Win-x86
Windows_NT-x86=Win-x86
Windows_NT_(unknown)-x86=Win-x86
Windows_Server_2008-x86=Win-x86
Windows_Vista-amd64=Win-x86
Windows_2003-amd64=Win-x86
Windows_2000-amd64=Win-x86
Windows_8-x86=Win-x86

Note: Only Windows_8-x86=Win-x86 line is added.

To override this file, you have to create a new file in the classpath with same name(platform-map.properties ) and copy above content into this file. If you use maven, copy this new file into resources folder.

Result

When you run ConnectorMXJObjectTestExample.java file, automatically a folder named as mysql-mxj is created in java.io.tmpdir location. In Windows, this location is C:\Users\{UserName}\AppData\Local\Temp

All necessary files for an embedded mysql database is located in the mysql-mxj folder. You can change this folder name if you want.

Database Name: our_test_app
Database Port: 3336
User Name: olyanren
Password: 1987

Some Important Notes

1. I created mysql-connector-mxj-gpl-db-files-5.0.12.jar file from this file by removing platforms except Windows platform.
2. After version 5.0.12, development of MySQL Connector/MXJ has been discontinued.
3. For more information, please click

To download our sample application, please click

© 2019 All rights reserved. Codesenior.COM