在Servlet和JSP中从数据库10g检索数据
There are countless ways of skinning this particular cat.
For one it depends on what Web framework (if any) you use. Personally I'm a huge fan of using Spring regardless of which Web framework you choose. It just makes so many things that much easier. Lightweight persistence frameworks include Spring JDBC and, my favourite, Ibatis .
In fact I wrote a tutorial on using Spring and Ibatis . In fact, it even uses Oracle 10g Express Edition ("Oracle XE").
Use (the ordering is my preference)
Don't use direct JDBC unless you just have a bunch of extra time.
Other answers have listed the best technologies that one should definitely pursue to accomplish this. But to directly answer the question, perhaps the most straight forward answer is with an example of plain old JDBC:
private void getYourData() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/yourDatabase");
conn = ds.getConnection();
pstmt = conn.prepareStatement(
"select yourdata " +
" from yourtable " +
" where yourkey = ? "
);
pstmt.setInt(1, yourKeyValue);
rset = pstmt.executeQuery();
while (rset.next()) {
String yourData = rset.getString("yourdata");
}
conn.commit();
} catch (NamingException ne) {
log.error(ne.getMessage());
} catch (SQLException se) {
log.error(se.getMessage());
} finally {
if (rset != null) {
try {
rset.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.