// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package mvcj;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DataX {
    private static DataSource ds;
    static {
        try {
            Context initctx = new InitialContext();
            Context envctx  = (Context)initctx.lookup("java:/comp/env");
            ds = (DataSource)envctx.lookup("jdbc/TestDB");
        } catch(NamingException ex) {
            ex.printStackTrace();
        }
    }
    public List<T1> selectAllT1() {
        List<T1> res = new ArrayList<T1>();
        try {
            Connection con = ds.getConnection();
            PreparedStatement pstmt = con.prepareStatement("SELECT f1,f2 FROM t1");
            ResultSet rs = pstmt.executeQuery();
            while(rs.next()) {
                int f1 = rs.getInt(1);
                String f2 = rs.getString(2);
                T1 o = new T1(f1, f2);
                res.add(o);
            }
            rs.close();
            pstmt.close();
            con.close();
        } catch(SQLException ex) {
            ex.printStackTrace();
        }
        return res;
    }
    public void insertOneT1(T1 o) {
        try {
            Connection con = ds.getConnection();
            PreparedStatement pstmt = con.prepareStatement("INSERT INTO t1 VALUES(?,?)");
            pstmt.setInt(1, o.getF1());
            pstmt.setString(2, o.getF2());
            pstmt.executeUpdate();
            pstmt.close();
            con.close();
        } catch(SQLException ex) {
            ex.printStackTrace();
        }
    }
    public void deleteOneT1(int f1) {
        try {
            Connection con = ds.getConnection();
            PreparedStatement pstmt = con.prepareStatement("DELETE FROM t1 WHERE f1 = ?");
            pstmt.setInt(1,  f1);
            pstmt.executeUpdate();
            pstmt.close();
            con.close();
        } catch(SQLException ex) {
            ex.printStackTrace();
        }
    }
}
