java简单操作h2数据库,目前使用sqlite3,所以这里只是备份。

    参考:https://www.jianshu.com/p/3663ef3fc93d

    1、引用

    1. <dependency>
    2. <groupId>com.h2database</groupId>
    3. <artifactId>h2</artifactId>
    4. <scope>runtime</scope>
    5. </dependency>

    2、示例

    1. public class H2Service {
    2. /**
    3. * 以嵌入式(本地)连接方式连接H2数据库,不能使用相对地址。
    4. */
    5. private static final String JDBC_URL = "jdbc:h2:~/h2.db";
    6. /**
    7. * 使用TCP/IP的服务器模式(远程连接)方式连接H2数据库(推荐)
    8. */
    9. // private static final String JDBC_URL = "jdbc:h2:tcp://10.35.14.122/C:/H2/user";
    10. private static final String USER = "root";
    11. private static final String PASSWORD = "root";
    12. private static final String DRIVER_CLASS = "org.h2.Driver";
    13. public static void main(String[] args) throws Exception {
    14. // TODO Auto-generated method stub
    15. Class.forName(DRIVER_CLASS);
    16. Connection conn = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
    17. Statement statement = conn.createStatement();
    18. statement.execute("DROP TABLE IF EXISTS USER_INF");
    19. statement.execute("CREATE TABLE USER_INF(id INTEGER PRIMARY KEY, name VARCHAR(100), sex VARCHAR(2))");
    20. statement.executeUpdate("INSERT INTO USER_INF VALUES(1, 'tom', '男') ");
    21. statement.executeUpdate("INSERT INTO USER_INF VALUES(2, 'jack', '女') ");
    22. statement.executeUpdate("INSERT INTO USER_INF VALUES(3, 'marry', '男') ");
    23. statement.executeUpdate("INSERT INTO USER_INF VALUES(4, 'lucy', '男') ");
    24. ResultSet resultSet = statement.executeQuery("select * from USER_INF");
    25. while (resultSet.next()) {
    26. System.out.println(
    27. resultSet.getInt("id") + ", " + resultSet.getString("name") + ", " + resultSet.getString("sex"));
    28. }
    29. statement.close();
    30. conn.close();
    31. }
    32. }

    结果:

    image.png