mariadb4j java代码
时间: 2023-07-09 14:23:15 浏览: 136
mariadb-java-client-2.7.3.zip
以下是使用 MariaDB4j 的 Java 代码示例:
```
import ch.vorburger.mariadb4j.DB;
import ch.vorburger.mariadb4j.DBConfigurationBuilder;
import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@Configuration
public class MariaDB4jConfig {
@Bean
public MariaDB4jSpringService mariaDB4jSpringService() throws Exception {
DBConfigurationBuilder config = DBConfigurationBuilder.newBuilder();
config.setPort(3307); // 设置端口号
config.setDataDir("target/mariadb4j/data"); // 设置数据目录
config.setBaseDir("target/mariadb4j"); // 设置 MariaDB 基础目录
DB db = DB.newEmbeddedDB(config.build());
db.start();
// 创建测试表格
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement("CREATE TABLE IF NOT EXISTS test (id INT PRIMARY KEY, name VARCHAR(255))");
ps.execute();
ps.close();
conn.close();
return new MariaDB4jSpringService(db);
}
@Bean
public DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService) throws SQLException {
return mariaDB4jSpringService.getDataSource();
}
// 测试代码
public static void main(String[] args) throws Exception {
MariaDB4jSpringService mariaDB4jSpringService = new MariaDB4jConfig().mariaDB4jSpringService();
DataSource dataSource = mariaDB4jSpringService.getDataSource();
Connection conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO test (id, name) VALUES (?, ?)");
ps.setInt(1, 1);
ps.setString(2, "Test");
ps.execute();
ps.close();
ps = conn.prepareStatement("SELECT * FROM test");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
ps.close();
conn.close();
mariaDB4jSpringService.getDB().stop();
}
}
```
这个示例代码创建了一个 MariaDB4jSpringService 实例,并在其中创建了一个测试表格。然后它使用创建的 MariaDB4jSpringService 实例连接到数据库,插入一条记录并读取记录。最后,它停止了 MariaDB 数据库。
阅读全文