2021-04-16 Java 链接PostgreSQL数据库

DemoPostgresApplication.java 

import java.sql.*;
import java.util.*;
import java.util.logging.Logger;

public class DemoPostgresApplication {

	private static final Logger log;

    static {
        System.setProperty("java.util.logging.SimpleFormatter.format", "[%4$-7s] %5$s %n");
        log =Logger.getLogger(DemoPostgresApplication.class.getName());
    }
    
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		log.info("Loading application properties");
		Properties properties = new Properties();
        properties.load(DemoPostgresApplication.class.getClassLoader().getResourceAsStream("postgresql.properties"));
        
        log.info("Connecting to the database");
        Connection connection = DriverManager.getConnection(properties.getProperty("jdbc.url"), properties.getProperty("jdbc.username"),properties.getProperty("jdbc.password"));
        log.info("Database connection test: " + connection.getCatalog());
        
        log.info("Create database schema");
        Scanner scanner = new Scanner(DemoPostgresApplication.class.getClassLoader().getResourceAsStream("./SQL/postgres.sql"));
        Statement statement = connection.createStatement();
        while (scanner.hasNextLine()) {
            statement.execute(scanner.nextLine());
        }
        
        log.info("Create Data"); 
        Todo todo = new Todo(1L, "configuration", "congratulations, you have set up JDBC correctly!", true);
        insertData(todo, connection);
        todo = readData(connection);
        todo.setDetails("congratulations, you have updated data!");
        updateData(todo, connection);
        deleteData(todo, connection);
        
        log.info("Closing database connection");
        connection.close();
        
        System.out.println("####################################################################");
        System.out.println("Postgres DB link CRUD successful!");
        System.out.println("####################################################################");
	}


	private static void deleteData(Todo todo, Connection connection) throws SQLException {
		// TODO Auto-generated method stub
	    log.info("Delete data");
	    PreparedStatement deleteStatement = connection.prepareStatement("DELETE FROM todo WHERE id = ?;");
	    deleteStatement.setLong(1, todo.getId());
	    deleteStatement.executeUpdate();
	    readData(connection);
	}

	private static void updateData(Todo todo, Connection connection) throws SQLException {
		// TODO Auto-generated method stub
	    log.info("Update data");
	    PreparedStatement updateStatement = connection
	            .prepareStatement("UPDATE todo SET description = ?, details = ?, done = ? WHERE id = ?;");

	    updateStatement.setString(1, todo.getDescription());
	    updateStatement.setString(2, todo.getDetails());
	    updateStatement.setBoolean(3, todo.isDone());
	    updateStatement.setLong(4, todo.getId());
	    updateStatement.executeUpdate();
	    readData(connection);	
	}

	private static Todo readData(Connection connection) throws SQLException {
		// TODO Auto-generated method stub
	    log.info("Read data");
	    PreparedStatement readStatement = connection.prepareStatement("SELECT * FROM todo;");
	    ResultSet resultSet = readStatement.executeQuery();
	    if (!resultSet.next()) {
	        log.info("There is no data in the database!");
	        return null;
	    }
	    Todo todo = new Todo();
	    todo.setId(resultSet.getLong("id"));
	    todo.setDescription(resultSet.getString("description"));
	    todo.setDetails(resultSet.getString("details"));
	    todo.setDone(resultSet.getBoolean("done"));
	    log.info("Data read from the database: " + todo.toString());
	    return todo;
	}

	private static void insertData(Todo todo, Connection connection) throws SQLException {
		// TODO Auto-generated method stub
	    log.info("Insert data");
	    PreparedStatement insertStatement = connection
	            .prepareStatement("INSERT INTO todo (id, description, details, done) VALUES (?, ?, ?, ?);");

	    insertStatement.setLong(1, todo.getId());
	    insertStatement.setString(2, todo.getDescription());
	    insertStatement.setString(3, todo.getDetails());
	    insertStatement.setBoolean(4, todo.isDone());
	    insertStatement.executeUpdate();
	}

}

Todo.java

public class Todo {
	private Long id;
	private String description;
	private String details;
	private boolean done;
	
	public Todo() {
	}

	public Todo(Long id, String description, String details, boolean done) {
		this.id = id;
		this.description = description;
		this.details = details;
		this.done = done;
	}
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getDetails() {
		return details;
	}
	public void setDetails(String details) {
		this.details = details;
	}
	public boolean isDone() {
		return done;
	}
	public void setDone(boolean done) {
		this.done = done;
	}
	
	@Override
	public String toString() {
		return "Todo{" + "id=" + id + ", description='" + description + '\'' + ", details='" + details + '\''
				+ ", done=" + done + '}';
	}
}

postgresql.properties

jdbc.driver=org.postgresql.Driver
jdbc.url=jdbc:postgresql://localhost:5432/postgres
jdbc.username=postgres
jdbc.password=postgres
initialSize=0
maxActive=20 
maxIdle=20
minIdle=1
maxWait=60000

Postgres.sql

DROP TABLE IF EXISTS todo;
CREATE TABLE todo (id SERIAL PRIMARY KEY, description VARCHAR(255), details VARCHAR(4096), done BOOLEAN);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值