Use of embedded MySQL in Java

  • 2020-05-16 06:56:00
  • OfStack

This document mainly introduces the use of embedded MySQL in Java. For some application projects, it is necessary to provide an installed version of Mysql and Oracle. But sometimes if it is a small tool, the installation or portability of a relatively strong small software. Installing the database can be tricky.

In fact, MySQL is also embedded and does not need to be installed. In the process of use, it will automatically create a database and start or close it by means of code. A few code snippets are provided below, with the download address provided.

This is the core code class that implements the startup and shutdown of Mysql and the startup state of the database.


package net.simple.mysql;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.mysql.management.MysqldResource;

/**
 * 
 * @author  Li Yanfei 
 * @email eliyanfei@126.com 
 * 2016 years 11 month 2 day   In the afternoon 1:44:55
 *
 */
public final class EmbedMySqlServer {
 private MysqldResource mysqlInstance;
 // Configuration information 
 public final Properties props;
 // Port information 
 private String port;
 /**
 *  Consider the performance of the database , Allows databases to be placed on other disks 
 */
 private String embedMySqlHome;

 public EmbedMySqlServer(final Properties props) {
 this.props = props;
 }

 public EmbedMySqlServer(final Properties props, String embedMySqlHome) {
 this.embedMySqlHome = embedMySqlHome;
 this.props = props;
 }

 public final String getEmbedMySqlHome() {
 return null == embedMySqlHome ? getPlatformBaseDir() : embedMySqlHome;
 }

 /**
 *  Gets the current application home directory 
 * @return  Directory where the current application launcher resides .
 */
 public static String getPlatformBaseDir() {
 return System.getProperty("user.dir");
 }

 public static boolean isBlank(final String str) {
 int strLen;
 if (str == null || (strLen = str.length()) == 0) {
  return true;
 }
 for (int i = 0; i < strLen; i++) {
  if (Character.isWhitespace(str.charAt(i)) == false) {
  return false;
  }
 }
 return true;
 }

 public void startup() {
 final File baseDir = new File(getEmbedMySqlHome(), "mysql-em");
 mysqlInstance = new MysqldResource(baseDir);
 port = props.getProperty("port");
 if (isBlank(port))
  props.put("port", port = String.valueOf((int) (Math.random() * 40000)));
 final Set<Object> keys = props.keySet();
 final Map<String, String> options = new HashMap<String, String>(keys.size());
 for (final Object key : keys) {
  final String val = props.getProperty(key.toString());
  if ("".equals(val))
  options.put(key.toString(), null);
  else
  options.put(key.toString(), val.replace("{$contextPath}", getPlatformBaseDir()));
 }
 if (!mysqlInstance.isRunning())
  mysqlInstance.start("Em_MySQL", options, false, keys.contains("defaults-file"));
 }

 public String getPort() {
 return port;
 }

 /**
 *  judge mysql Is it running 
 */
 public boolean isRunning() {
 return null == mysqlInstance ? false : mysqlInstance.isRunning();
 }

 public void shutdown() {
 if (mysqlInstance != null)
  mysqlInstance.shutdown();
 }

 public void cleanup() {
 if (mysqlInstance != null)
  mysqlInstance.cleanup();
 }
}

So this is starting Demo,


public static void main(String[] args) {
 try {
  Properties pro = new Properties();
  // Depending on the machine configuration, set different parameters 
  pro.load(MysqlTest.class.getResourceAsStream("MySql_medium.properties"));
  new EmbedMySqlServer(pro).startup();
  // You can put the database on another disk 
  //new EmbedMySqlServer(pro,"f:\\").startup();
  Connection conn = getTestConnection();
  System.out.println(conn.isClosed());
  conn.close();
 } catch (Exception e) {
  e.printStackTrace();
 }
 }

Sample configuration of MySql_general.properties1-like machine

Sample configuration of MySql_medium.properties medium machine

MySql_large.properties configuration sample

Specific parameters can be defined according to different requirements, such as ports can be freely defined.

mysql two jar, mysql-connector-mxj-gpl-6-0-11-db-files. jar, mysql-connector-mxj-gpl-6-0-11.jar

Code on Git, address is: https: / / git oschina. net/eliyanfei/api_tools git


Related articles: