糯米文學吧

位置:首頁 > 計算機 > java語言

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

java語言3.07W

這篇文件主要介紹在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 嵌入式