如何关闭h2内存数据库?

4

如果最后一个连接关闭,则内存数据库将关闭。

问题是如何手动强制关闭内存数据库?

因为我需要测试当连接断开或数据源不可用时的情况。在生产环境中,所有这些都会发生,我想在测试中模拟这种情况。

1个回答

2

好的,我想要的是TCP+MEM+EMBEDED服务器。

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();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接