package org.clzps.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.clzps.dao.CustomerDAO;
import org.clzps.model.Customer;
public class JdbcCustomerDAO implements CustomerDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Customer findByCustomerId(int custId) {
String sql = "SELECT * FROM Customer WHERE cust_id = ? " ;
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1, custId);
Customer customer = null;
ResultSet rs = pst.executeQuery();
if(rs.next()) {
customer = new Customer();
customer.setCustid(rs.getInt("cust_id"));
customer.setName(rs.getString("name"));
customer.setAge(rs.getInt("age"));
}
rs.close();
pst.close();
return customer;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
public void insert(Customer customer) {
String sql = "INSERT INTO customer (name, age) VALUES (?, ?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, customer.getName());
pst.setInt(2, customer.getAge());
pst.executeUpdate();
pst.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
}