使用Commons DbUtils进行JDBC数据库连接
文章目录
首先直接把jar包放在/WebContent/WEB-INF/lib目录下。 通过buildpath添加可能会有异常。
MessageArchiever.java
{% codeblock lang:java %}
import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.text.SimpleDateFormat;
import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource;
//使用QueryRunner类进行数据库操作 import org.apache.commons.dbutils.QueryRunner;
import javax.naming.Context; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/**
-
Servlet implementation class MessageArchiever */ @WebServlet(description = “Stores all valid users’ message.", urlPatterns = { “/MessageArchiever” }) public class MessageArchiever extends HttpServlet { private static final long serialVersionUID = 1L;
/**
- @see HttpServlet#HttpServlet() */ public MessageArchiever() { super(); // TODO Auto-generated constructor stub }
/**
- @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
-
response)
*/ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append(“Served at: “).append(request.getContextPath()); }
/**
- @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
-
response)
*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int result = 0; // 设置编码 request.setCharacterEncoding("utf-8"); // 要执行的SQL语句 String sql = "insert into book(name,email,phone,title,content,publishtime) values(?,?,?,?,?,?)"; String name = request.getParameter("name"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); String topic = request.getParameter("topic"); String content = request.getParameter("content"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String param[] = { name, email, phone, topic, content, sdf.format(new java.util.Date()) }; try { // 初始化上下文环境,可以从这个环境中取出数据源对象 Context context = new InitialContext(); // 从上下文环境中取出数据源对象,其中jdbc/mysql就是我们在DBCP中配置的数据库源,这个数据库受DBCP的管理 DataSource dSource = (DataSource) context.lookup("java:/comp/env/jdbc/mysql"); QueryRunner qRunner = new QueryRunner(dSource); result = qRunner.update(sql, param); response.getWriter().append(Integer.toString(result)); } catch (NamingException | SQLException e) { e.printStackTrace(); } doGet(request, response);
}
} {% endcodeblock %}