I am creating a polling program in java using TimerTask for to send email and other notifications automatically. Now this program every second check the database for any new data available.
Now i am creating connection like below
Connector class its holds database details and return a connection.
public class Connector implements Serializable {
private static final long serialVersionUID = 1L;
private ResourceBundle prop = ResourceBundle.getBundle("dbdetails");
public Connection getConnection() throws Exception {
Connection con;
Class.forName((String) prop.getString("DB_DRIVER"));
con = DriverManager.getConnection((String) prop.getString("DB_URL"),
(String) prop.getString("DB_USER"),
(String) prop.getString("DB_PASS"));
return con;
}
}
My polling class
public class EmailPoller extends TimerTask {
private static Logger logger = Logger.getLogger(EmailPoller.class);
private Connector connector = new Connector();
@Override
public void run() {
Connection con = null;
PreparedStatement ps = null, ps1 = null;
ResultSet rs = null;
try {
con = connector.getConnection();
ps = con.prepareStatement("select to_addr,subject,content,id from email_notification where status='A'");
ps1 = con
.prepareStatement("update email_notification set status='I' where id=?");
rs = ps.executeQuery();
while (rs.next()) {
Boolean b = Mailer.sendMail(rs.getString(1), rs.getString(2),
rs.getString(3));
if (b) {
ps1.setInt(1, rs.getInt(4));
ps1.executeUpdate();
}
}
} catch (Exception ex) {
logger.info("Email Poller Error : " + ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (ps1 != null) {
ps1.close();
}
if (con != null) {
con.close();
}
} catch (Exception ex) {
logger.info("Email Poller Error : " + ex);
}
}
}
}
after send a email i am updating a flag. Mailer is sending mail perfectly.
Whether this is a correct approach to check the database for data or any other best way is there to connect to the database?