【问题标题】:How to close h2 in-memory database?如何关闭 h2 内存数据库?
【发布时间】:2014-11-14 02:16:33
【问题描述】:

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

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

因为我需要在连接断开或者DataSource不可用的情况下进行测试。在生产中,这一切都会发生,我想模拟测试中的情况。

【问题讨论】:

    标签: java database h2


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 2017-06-16
      • 2011-01-19
      • 2012-08-17
      相关资源
      最近更新 更多