簡體   English   中英

如何關閉h2內存數據庫?

[英]How to close h2 in-memory database?

如果最后一個連接關閉,內存數據庫將關閉。

問題是如何強制關閉內存手冊?

因為我需要測試連接何時關閉,或者當DataSource不可用時。在生產中,所有這些都會發生,我想模擬測試中的情況。

好的,TCP + MEM + EMBEDED 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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM