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

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

public class ContactsDatabaseAccess {
    public static void insert(Contacts c) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test");
        Statement stmt = con.createStatement();
        stmt.executeUpdate("INSERT INTO contacts(name,phone,email) VALUES ('" + c.getName() + "','" + c.getPhone() + "','" + c.getEmail() + "')");
        stmt.close();
        con.close();
    }
    public static List getAll() throws ClassNotFoundException, SQLException {
        List res = new ArrayList();
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT name,phone,email FROM contacts");
        while(rs.next()) {
            Contacts c = new Contacts();
            c.setName(rs.getString("name"));
            c.setPhone(rs.getString("phone"));
            c.setEmail(rs.getString("email"));
            res.add(c);
        }
        rs.close();
        stmt.close();
        con.close();
        return res;
    }
}
