這篇文件主要介紹在Java中嵌入式MySQL的使用,對于一些的應(yīng)用項目,提供安裝版的Mysql,Oracle是必須的工作。但是有時候如果是一個小的工具,可安裝或者移植性比較強的小軟件。再去安裝數(shù)據(jù)庫可能就比較麻煩了。
其實MySQL也有嵌入式的,不需要安裝,在使用的過程中,會自動創(chuàng)建數(shù)據(jù)庫以及通過代碼的方式啟動或者關(guān)閉。下面提供一些代碼片段,具體的會提供下載地址。
這個是核心代碼類,這個類實現(xiàn)了Mysql 的啟動和停止以及數(shù)據(jù)庫的啟動狀態(tài)。
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; public final class EmbedMySqlServer { private MysqldResource mysqlInstance; //配置信息 public final Properties props; //端口信息 private String port; /** * 考慮到數(shù)據(jù)庫的性能問題,允許將數(shù)據(jù)庫放在其它磁盤 */ 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; } /** * 獲得當(dāng)前應(yīng)用主目錄 * @return 當(dāng)前應(yīng)用啟動程序所在目錄. */ 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; } /** * 判斷mysql是否正在運行 */ 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(); } }
下面這個是啟動Demo,
public static void main(String[] args) { try { Properties pro = new Properties(); //根據(jù)機器配置,設(shè)置不同的參數(shù) pro.load(MysqlTest.class.getResourceAsStream("MySql_medium.properties")); new EmbedMySqlServer(pro).startup(); //可以把數(shù)據(jù)庫放到其他磁盤 //new EmbedMySqlServer(pro,"f:\\").startup(); Connection conn = getTestConnection(); System.out.println(conn.isClosed()); conn.close(); } catch (Exception e) { e.printStackTrace(); } }
MySql_general.properties一般機器的配置樣例
MySql_medium.properties中等機器的配置樣例
MySql_large.properties高配機的配置樣例
具體的參數(shù)可以根據(jù)不同需求進行定義,比如端口可以自由定義。
需要引用的mysql兩個jar,mysql-connector-mxj-gpl-6-0-11-db-files.jar,mysql-connector-mxj-gpl-6-0-11.jar

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded

CTE is a temporary result set in MySQL used to simplify complex queries. It can be referenced multiple times in the current query, improving code readability and maintenance. For example, when looking for the latest orders for each user in the orders table, you can first obtain the latest order date for each user through the CTE, and then associate it with the original table to obtain the complete record. Compared with subqueries, the CTE structure is clearer and the logic is easier to debug. Usage tips include explicit alias, concatenating multiple CTEs, and processing tree data with recursive CTEs. Mastering CTE can make SQL more elegant and efficient.

High-frequency questions in Java interviews are mainly focused on basic syntax, object-oriented, multithreaded, JVM and collection frameworks. The most common questions include: 1. There are 8 basic Java data types, such as byte, short, int, long, float, double, char and boolean. It is necessary to note that String is not the basic data type; 2. Final is used to modify classes, methods or variables to represent immutable, and finally is used to ensure code execution in exception processing. Finalize is an Object class method for cleaning before garbage collection; 3. Multi-thread synchronization can be achieved through synchronized keywords, ReentrantLock, and vo.

The method of using preprocessing statements to obtain database query results in PHP varies from extension. 1. When using mysqli, you can obtain the associative array through get_result() and fetch_assoc(), which is suitable for modern environments; 2. You can also use bind_result() to bind variables, which is suitable for situations where there are few fields and fixed structures, and it is good compatibility but there are many fields when there are many fields; 3. When using PDO, you can obtain the associative array through fetch (PDO::FETCH_ASSOC), or use fetchAll() to obtain all data at once, so the interface is unified and the error handling is clearer; in addition, you need to pay attention to parameter type matching, execution of execute(), timely release of resources and enable error reports.

Create and use SimpleDateFormat requires passing in format strings, such as newSimpleDateFormat("yyyy-MM-ddHH:mm:ss"); 2. Pay attention to case sensitivity and avoid misuse of mixed single-letter formats and YYYY and DD; 3. SimpleDateFormat is not thread-safe. In a multi-thread environment, you should create a new instance or use ThreadLocal every time; 4. When parsing a string using the parse method, you need to catch ParseException, and note that the result does not contain time zone information; 5. It is recommended to use DateTimeFormatter and Lo

WhensettingupMySQLtables,choosingtherightdatatypesiscrucialforefficiencyandscalability.1)Understandthedataeachcolumnwillstore—numbers,text,dates,orflags—andchooseaccordingly.2)UseCHARforfixed-lengthdatalikecountrycodesandVARCHARforvariable-lengthdata

BiConsumer is a functional interface in Java that handles operations that do not return results. It belongs to the java.util.function package and is suitable for scenarios where two data are required to operate at the same time, such as key-value pairs that traverse Map. A common usage is to iterate with Map's forEach method. Unlike other functional interfaces such as Consumer and BiFunction, BiConsumer does not generate a return value. The implementation methods include lambda expressions, method references and anonymous classes. When using them, you need to pay attention to the order of type parameters, non-returnable values, and exception handling.
