您当前的位置: 首页 >  Java

彭世瑜

暂无认证

  • 0浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java:H2数据库使用示例

彭世瑜 发布时间:2020-12-09 22:47:54 ,浏览量:0

参考文档:http://h2database.com/html/main.html

依赖


    com.h2database
    h2
    1.4.200

代码示例

package com.demo.h2;

import java.sql.*;

public class H2Demo {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        String url = "jdbc:h2:./database";
        String driverClass = "org.h2.Driver";

        Class.forName(driverClass);

        Connection connection = DriverManager.getConnection(url);


        Statement statement = connection.createStatement();

        // 创建数据表
        statement.execute("DROP TABLE IF EXISTS user");
        statement.execute("create table user(id int(11) primary key auto_increment, name varchar(20))");

        // 添加数据
        statement.executeUpdate("insert into user(name) values('刘备')");
        statement.executeUpdate("insert into user(name) values('关羽')");
        statement.executeUpdate("insert into user(name) values('张飞')");

        // 查询数据
        ResultSet resultSet = statement.executeQuery("select * from user");

        while (resultSet.next()){
            Integer id = resultSet.getInt("id");
            String name = resultSet.getString("name");

            System.out.println("id: " + id + ", name: " + name);
        }

        // 关闭链接
        resultSet.close();
        statement.close();
        connection.close();

    }
}

使用IDEA打开的时候,如果连接不上,可以试试配置路径不要写后缀database.mv.db -> database

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.3104s