forked from IBM/openshift-workshop-was
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJdbcServlet.java
More file actions
68 lines (59 loc) · 2.35 KB
/
JdbcServlet.java
File metadata and controls
68 lines (59 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package wasdev.sample.jdbc;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
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;
/**
* Servlet implementation class JdbcServlet
*/
@WebServlet("/*")
public class JdbcServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Resource(name = "jdbc/exampleDS")
DataSource ds1;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Statement stmt = null;
Connection con = null;
try {
con = ds1.getConnection();
stmt = con.createStatement();
// create a table
stmt.executeUpdate("create table cities (name varchar(50) not null primary key, population int, county varchar(30))");
// insert a test record
stmt.executeUpdate("insert into cities values ('myHomeCity', 106769, 'myHomeCounty')");
// select a record
ResultSet result = stmt.executeQuery("select county from cities where name='myHomeCity'");
result.next();
// display the county information for the city.
response.getWriter().print("<html><h1><font color=green>Text retrieved from database is: </font></html>" +
"<html><font color=red>" + result.getString(1) + "</font></h1></html>");
//System.out.println("The county for myHomeCity is " + result.getString(1));
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
// drop the table to clean up and to be able to rerun the test.
stmt.executeUpdate("drop table cities");
} catch (SQLException e) {
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}