package sklep.serwlety;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

@WebServlet("/sql3")
public class Sql3 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Resource(lookup="java:/sklep_ds")
	private DataSource ds;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();

		try {
			out.println("DataSource wstrzyknięty: " + ds);
			
			final String sql = "SELECT * FROM products";
			try (Connection c = ds.getConnection()) {
				try (PreparedStatement stmt = c.prepareStatement(sql)) {
					try (ResultSet rs = stmt.executeQuery()) {
						while (rs.next()) {
							int id = rs.getInt("product_id");
							String productName = rs.getString("product_name");
							BigDecimal price = rs.getBigDecimal("price");
							String description = rs.getString("description");
							out.printf("\n * Produkt nr %d: %s w cenie %s (%s)\n", id, productName, price, description);
						}
					}
				}
			}
		} catch (SQLException e) {
			e.printStackTrace(out);
		} catch (Exception e) {
			e.printStackTrace(out);
		}
	}

}
