KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mockobjects > examples > mailinglist > MailingList


1 package com.mockobjects.examples.mailinglist;
2
3 import java.sql.*;
4
5 public class MailingList {
6     static public final String JavaDoc INSERT_SQL = "insert into mailing_list(email_address, name) values(?, ?)";
7     static public final String JavaDoc DELETE_SQL = "delete from mailing_list where email_address = ?";
8     static public final String JavaDoc LIST_SQL = "select * from mailing_list";
9
10     public void addMember(Connection connection, String JavaDoc emailAddress, String JavaDoc name) throws MailingListException, SQLException {
11         PreparedStatement statement = connection.prepareStatement(INSERT_SQL);
12         try {
13             statement.setString(1, emailAddress);
14             statement.setString(2, name);
15             statement.execute();
16         } catch (SQLException ex) {
17             if (ex.getErrorCode() == DatabaseConstants.UNIQUE_CONSTRAINT_VIOLATED) {
18                 throw new MailingListException("Email address exists: " + emailAddress);
19             } else {
20                 throw ex;
21             }
22         } finally {
23             statement.close();
24         }
25     }
26
27     public void removeMember(Connection connection, String JavaDoc emailAddress) throws MailingListException, SQLException {
28         PreparedStatement statement = connection.prepareStatement(DELETE_SQL);
29         try {
30             statement.setString(1, emailAddress);
31             if (statement.executeUpdate() == 0) {
32                 throw new MailingListException("Could not find email address: " + emailAddress);
33             }
34         } finally {
35             statement.close();
36         }
37     }
38
39     public void applyToAllMembers(Connection connection, ListAction listMembers) throws MailingListException, SQLException {
40         Statement statement = connection.createStatement();
41         try {
42             ResultSet results = statement.executeQuery(LIST_SQL);
43
44             while (results.next()) {
45                 listMembers.applyTo(results.getString("email_address"), results.getString("name"));
46             }
47         } finally {
48             statement.close();
49         }
50     }
51 }
52
Popular Tags