| |
25. 33. 2. Servlet更新数据库 |
|
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:ordersdb", "user", "passwd");
// Turn on transactions
con.setAutoCommit(false);
Statement stmt = con.createStatement();
stmt.executeUpdate("UPDATE INVENTORY SET STOCK = (STOCK - 10) ");
stmt.executeUpdate("UPDATE SHIPPING SET SHIPPED = (SHIPPED + 10)");
con.commit();
out.println("Order successful! Thanks for your business!");
}
catch (Exception e) {
// Any error is grounds for rollback
try {
con.rollback();
}
catch (SQLException ignored) { }
out.println("Order failed. Please contact technical support.");
}
finally {
// Clean up.
try {
if (con != null) con.close();
}
catch (SQLException ignored) { }
}
}
}
|
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet><servlet-name>MyServletName</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping><servlet-name>MyServletName</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.timeZone</param-name>
<param-value>US/Central</param-value>
</context-param>
<context-param>
<param-name>database-driver</param-name>
<param-value>org.gjt.mm.mysql.Driver</param-value>
</context-param>
<context-param>
<param-name>database-url</param-name>
<param-value>
jdbc:mysql://localhost/forum?user=forumuser</param-value>
</context-param>
</web-app>
|
|
Download: ServletUpdateDatabase.zip( 1,067 k) |
|