1、引入依赖

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.16</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.7.4</version>
        </dependency>

2、示例代码

package com.soft863.common.db;

import cn.hutool.db.Db;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import org.postgresql.ds.PGSimpleDataSource;
import java.sql.SQLException;
import java.util.List;

public class Student {

    private int sid;
    private String gender;

    private int class_id;
    private String sname;

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getClass_id() {
        return class_id;
    }

    public void setClass_id(int class_id) {
        this.class_id = class_id;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", gender='" + gender + '\'' +
                ", class_id='" + class_id + '\'' +
                ", sname='" + sname + '\'' +
                '}';
    }

    public static void main(String[] args) {
        PGSimpleDataSource dataSource = new PGSimpleDataSource();
        dataSource.setServerName("localhost");
        dataSource.setDatabaseName("skynet");
        dataSource.setUser("postgres");
        dataSource.setPassword("postgres");

        Db db = DbUtil.use(dataSource);

        // 查询案例
        List<Student> result = null;
        try {
            result = db.query("select * from student", Student.class);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        for (Student stu : result) {
            System.out.println(stu);
        }

        System.out.println("==========================================================================================");

        Entity entity = Entity.create("student")
                .set("sid", 3)
                .set("sname", "小明")
                .set("class_id", 1)
                .set("gender", "男");
        try {
            int affectedRows = db.insert(entity);
            System.out.println(affectedRows);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐