当前位置:学者斋 >

计算机 >java语言 >

Java中嵌入式MySQL的使用方法介绍

Java中嵌入式MySQL的使用方法介绍

这篇文件主要介绍在Java中嵌入式MySQL的使用,对于一些的应用项目,提供安装版的Mysql,Oracle是必须的工作。但是有时候如果是一个小的工具,可安装或者移植性比较强的小软件。再去安装数据库可能就比较麻烦了。

Java中嵌入式MySQL的使用方法介绍

其实MySQL也有嵌入式的,不需要安装,在使用的过程中,会自动创建数据库以及通过代码的方式启动或者关闭。下面提供一些代码片段,具体的会提供下载地址。

  这个是核心代码类,这个类实现了Mysql 的启动和停止以及数据库的启动状态。

package l;import ;import Map;import ;import erties;import ;import ldResource;/** * * @author 李岩飞 * @email * 2016年11月2日 下午1:44:55 * */public final class EmbedMySqlServer { private MysqldResource mysqlInstance; //配置信息 public final Properties props; //端口信息 private String port; /** * 考虑到数据库的性能问题,允许将数据库放在其它磁盘 */ private String embedMySqlHome; public EmbedMySqlServer(final Properties props) { s = props; } public EmbedMySqlServer(final Properties props, String embedMySqlHome) { dMySqlHome = embedMySqlHome; s = props; } public final String getEmbedMySqlHome() { return null == embedMySqlHome ? getPlatformBaseDir() : embedMySqlHome; } /** * 获得当前应用主目录 * @return 当前应用启动程序所在目录. */ public static String getPlatformBaseDir() { return roperty(""); } public static boolean isBlank(final String str) { int strLen; if (str == null || (strLen = th()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (itespace(At(i)) == false) { return false; } } return true; } public void startup() { final File baseDir = new File(getEmbedMySqlHome(), "mysql-em"); mysqlInstance = new MysqldResource(baseDir); port = roperty("port"); if (isBlank(port)) ("port", port = eOf((int) (om() * 40000))); final Set

keys = et(); final Mapoptions = new HashMap(()); for (final Object key : keys) { final String val = roperty(ring()); if (""ls(val)) (ring(), null); else (ring(), ace("{$contextPath}", getPlatformBaseDir())); } if (!nning()) t("Em_MySQL", options, false, ains("defaults-file")); } public String getPort() { return port; } /** * 判断mysql是否正在运行 */ public boolean isRunning() { return null == mysqlInstance ? false : nning(); } public void shutdown() { if (mysqlInstance != null) down(); } public void cleanup() { if (mysqlInstance != null) nup(); }}

  下面这个是启动Demo,

public static void main(String[] args) { try { Properties pro = new Properties(); //根据机器配置,设置不同的参数 (esourceAsStream("MySql_erties")); new EmbedMySqlServer(pro)tup(); //可以把数据库放到其他磁盘 //new EmbedMySqlServer(pro,"f:")tup(); Connection conn = getTestConnection(); tln(osed()); e(); } catch (Exception e) { tStackTrace(); } }

MySql_erties一般机器的.配置样例

MySql_erties中等机器的配置样例

MySql_erties高配机的配置样例

具体的参数可以根据不同需求进行定义,比如端口可以自由定义。

需要引用的mysql两个jar,,

代码在Git上,地址是:_

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签: JAVA MySQL 嵌入式
  • 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/0lm140.html