01: package example;
02:
03: import java.io.PrintWriter;
04:
05: import java.sql.Connection;
06: import java.sql.Statement;
07: import java.sql.ResultSet;
08: import java.sql.SQLException;
09:
10: import javax.sql.DataSource;
11:
12: import javax.servlet.ServletException;
13:
14: import javax.servlet.http.HttpServlet;
15: import javax.servlet.http.HttpServletRequest;
16: import javax.servlet.http.HttpServletResponse;
17:
18: import javax.webbeans.In;
19:
20: /**
21: * The InitServlet initializes the database.
22: *
23: */
24: public class InitServlet extends HttpServlet {
25: /**
26: * The DataSource for the table.
27: */
28: @In
29: private DataSource _ds;
30:
31: /**
32: * Initializes the reference to the CourseBean home interface.
33: */
34: public void init() throws ServletException {
35: try {
36: Connection conn = _ds.getConnection();
37:
38: try {
39: Statement stmt = conn.createStatement();
40:
41: try {
42: ResultSet rs = stmt
43: .executeQuery("SELECT id FROM jdbc_basic_brooms");
44:
45: if (rs.next()) {
46: rs.close();
47: stmt.close();
48: return; // already initialized
49: }
50: } catch (SQLException e) {
51: }
52:
53: stmt.executeUpdate("CREATE TABLE jdbc_basic_brooms ("
54: + " id INTEGER PRIMARY KEY auto_increment,"
55: + " name VARCHAR(128)," + " cost INTEGER"
56: + ")");
57: stmt
58: .executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) "
59: + "VALUES ('firebolt', 4000)");
60: stmt
61: .executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) "
62: + "VALUES ('nimbus 2001', 500)");
63: stmt
64: .executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) "
65: + "VALUES ('nimbus 2000', 300)");
66: stmt
67: .executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) "
68: + "VALUES ('cleansweep 7', 150)");
69: stmt
70: .executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) "
71: + "VALUES ('cleansweep 5', 100)");
72: stmt
73: .executeUpdate("INSERT INTO jdbc_basic_brooms (name, cost) "
74: + "VALUES ('shooting star', 50)");
75:
76: stmt.close();
77: } finally {
78: conn.close();
79: }
80: } catch (SQLException e) {
81: throw new ServletException(e);
82: }
83: }
84:
85: /**
86: *
87: */
88: public void service(HttpServletRequest req, HttpServletResponse res)
89: throws java.io.IOException, ServletException {
90: throw new UnsupportedOperationException();
91: }
92: }
|