嵌入式mysql

琴献
2023-12-01

1 潜入式mysql

1.1 引入包

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

1.2 编写java

	String port = getPort(properties);
		String userName = getUserName(properties);
		String password = getPassword(properties);

		mysqldResource = new MysqldResource(baseDir, dataDir);

		Map<String, Object> dbOption = new HashMap<String, Object>();
		dbOption.put(MysqldResourceI.PORT, port);
		dbOption.put(MysqldResourceI.INITIALIZE_USER, "true");
		dbOption.put(MysqldResourceI.INITIALIZE_USER_NAME, userName);
		dbOption.put(MysqldResourceI.INITIALIZE_PASSWORD, password);

		if (clop.isShutdown()) {
			mysqldResource.shutdown();
			return false;
		}

		mysqldResource.start("mysqld", dbOption);

		if (!mysqldResource.isRunning()) {
			throw new RuntimeException("MySQL did not start.");
		}
		System.out.println("MySQL is running.");

1.3 创建数据库

private void createDatabase(Properties properties) {
		String DRIVER = "com.mysql.jdbc.Driver";

		Connection conn = null;
		try {
			Class.forName(DRIVER);
			String url = "jdbc:mysql://localhost:" + this.getPort(properties) + "/" + this.getDbName(properties) + "?"
					+ "createDatabaseIfNotExist=true&characterEncoding=utf8";
			conn = DriverManager.getConnection(url, getUserName(properties), getPassword(properties));
			String sql = "SELECT VERSION()";
			String queryForString = new QueryUtil(conn).queryForString(sql);

			new QueryUtil(conn).execute("alter database " + this.getDbName(properties) + " character set utf8");
			new QueryUtil(conn).execute("set character_set_server=utf8");
			new QueryUtil(conn).execute("grant all privileges on *.* to 'root'@'%' identified by 'root'");
			new QueryUtil(conn).execute("flush privileges");

			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

		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

1.4 copy kill

把 kill.exe 复制到 c-mxj-utils 目录下, 下次重启可以杀mysql进程, 也可以编写停止mysql 方法.

 类似资料: