java - 如何关闭 h2 内存数据库?

标签 java database h2

The in-memory database will close if the last connection is closed.

问题是如何强制关闭内存手册?

因为我需要测试什么时候连接断开,或者什么时候DataSource不可用。在生产中,这些都会发生,我想在测试中模拟这种情况。

最佳答案

OK,TCP+MEM+EMBEDDED SERVER就是我想要的

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.tools.Server;
import org.junit.Before;
import org.junit.Test;

public class H2ServerDownTest
{

    private Server server;

    @Before
    public void startServer() throws SQLException
    {
//        TCP server only.
        server = Server.createTcpServer("-tcp -webPort 8008 -tcpPort 9008 -properties null".split(" "));
        System.out.println("Start Server AT: " + server.getURL());
    }

    @Test(expected = SQLException.class)
    public void test() throws SQLException
    {
        server.start();
        Connection c = getConnection();
        Statement stmt = c.createStatement();
        stmt.execute("create table test(id int primary key, val varchar(100))");
        for (int i = 0; i < 1000; i++)
        {
            if (i == 500)
            {
                server.stop();
            }
            stmt.execute("insert into test values(" + i + ", 'values')");
        }
    }

    public Connection getConnection() throws SQLException
    {
        return DriverManager.getConnection("jdbc:h2:"+server.getURL()+"/mem:db", "sa", "");
    }

    @Test
    public void shutdownServer()
    {
        server.shutdown();
    }
}

关于java - 如何关闭 h2 内存数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26921842/

相关文章:

java - Character.isLetter 是否需要标准化文本?

django - 将数据库与弹性 beanstalk 一起使用

database - MongoLab _id 字段

java - tomcat 环境中的 H2 数据库在选择 sequence.nextval 时抛出 RuntimeException "unexpected code path"

spring-security - .headers().frameOptions().disable() 是如何工作的?

Java读入一个文本文件,然后分成单独的数组

java - 使用 spring jdbctemplate 的 Sql Server

python - Django 管理页面不显示数据库表(djangobook 第 06 章)

java - Oracle 查询中的 H2 加/减间隔秒

java - Spring Batch 多线程 - 如何让每个线程读取唯一记录?