Can I have H2 autocreate a schema in an in-memory database?

后端 未结 5 2000
逝去的感伤
逝去的感伤 2020-11-30 20:36

(I\'ve already seen the H2 database In memory - Init schema via Spring/Hibernate question; it is not applicable here.)

I\'d like to know if there\'s a setting in H2

5条回答
  •  醉酒成梦
    2020-11-30 21:02

    "By default, when an application calls DriverManager.getConnection(url, ...) and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.

    Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    /** @see http://stackoverflow.com/questions/5225700 */
    public class H2MemTest {
    
        public static void main(String[] args) throws Exception {
            Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
            Statement st = conn.createStatement();
            st.execute("create table customer(id integer, name varchar(10))");
            st.execute("insert into customer values (1, 'Thomas')");
            Statement stmt = conn.createStatement();
            ResultSet rset = stmt.executeQuery("select name from customer");
            while (rset.next()) {
                String name = rset.getString(1);
                System.out.println(name);
            }
        }
    }
    

提交回复
热议问题