// 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;

public class Data {
    public List<T1> selectAllT1() {
        List<T1> res = new ArrayList<T1>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            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(ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch(SQLException ex) {
            ex.printStackTrace();
        }
        return res;
    }
    public void insertOneT1(T1 o) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            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(ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch(SQLException ex) {
            ex.printStackTrace();
        }
    }
    public void deleteOneT1(int f1) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
            PreparedStatement pstmt = con.prepareStatement("DELETE FROM t1 WHERE f1 = ?");
            pstmt.setInt(1,  f1);
            pstmt.executeUpdate();
            pstmt.close();
            con.close();
        } catch(ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch(SQLException ex) {
            ex.printStackTrace();
        }
    }
}
