// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package akkademo2.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PersistJDBC {
	private String conurl;
	public PersistJDBC(String conurl) {
		this.conurl = conurl;
	}
	public int getValue(int id) throws SQLException {
		try(Connection con = DriverManager.getConnection(conurl)) {
			try(PreparedStatement pstmt = con.prepareStatement("SELECT val FROM demo WHERE id = ?")) {
				pstmt.setInt(1, id);
				try(ResultSet rs = pstmt.executeQuery()) {
					if(rs.next()) {
						return rs.getInt(1);
					} else {
						return -1;
					}
				}
			}
		}
	}
	public void setValue(int id, int val) throws SQLException {
		try(Connection con = DriverManager.getConnection(conurl)) {
			try(PreparedStatement pstmt = con.prepareStatement("UPDATE demo SET val = ? WHERE id = ?")) {
				pstmt.setInt(1, val);
				pstmt.setInt(2, id);
				pstmt.executeUpdate();
			}
		}
	}
}
