HttpServlet 实现 MySQL 数据库的插入操作
MySQL 数据库及表的创建过程,请参考前文《MySQL 数据库及数据表的创建》。
本文重点来分步进行 HttpServlet 中,MySQL 数据库的插入操作实现。
实现步骤
1. 准备数据库的地址、用户名和密码
public static final String url = "jdbc:mysql://localhost:3306/budaye_test01";public static final String name = "root";public static final String pass = "123456";
数据库地址:MySQL 数据库创建完成后,本地地址默认都是:jdbc:mysql://localhost:3306。budaye_test01:是数据库的名称,这里已经创建好了,创建过程参考前文。root:是数据库的用户名。pass:数据库用户名多对应的密码。
2. 加载数据库
Class.forName("com.mysql.cj.jdbc.Driver");
这里注意,com.mysql.jdbc.Driver 已弃用。
3. 连接数据库
Connection conn = null;conn = DriverManager.getConnection(url, name, pass);
4. 插入数据库
// 读请求参数String parName = request.getParameter("name");String age = request.getParameter("age");PreparedStatement prep = null;prep = conn.prepareStatement("insert into " + "name_table(name,age) " + "values(?,?)");prep.setString(1, parName);prep.setDouble(2, Integer.parseInt(age));prep.executeUpdate();
完整代码
public class UpdateNowList extends HttpServlet {private static final long serialVersionUID = 1L;public static final String url = "jdbc:mysql://localhost:3306/budaye_test01";public static final String name = "root";public static final String pass = "mima";Connection conn = null;/*** @see HttpServlet#HttpServlet()*/public UpdateNowList() {super();}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse*response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 设置响应内容类型response.setContentType("text/html;charset=UTF-8");PrintWriter out = response.getWriter();// 读请求参数String parName = request.getParameter("name");String age = request.getParameter("age");PreparedStatement prep = null;try {// Class.forName("com.mysql.jdbc.Driver"); //已被弃用Class.forName("com.mysql.cj.jdbc.Driver");System.out.println("Success loading Mysql Driver!");conn = DriverManager.getConnection(url, name, pass);System.out.println("Success connect Mysql server!");prep = conn.prepareStatement("insert into " + "name_table(name,age) " + "values(?,?)");prep.setString(1, parName);prep.setDouble(2, Integer.parseInt(age));prep.executeUpdate();out.println("插入成功");} catch (Exception e) {// 记日志e.printStackTrace();out.println("连接数据库失败,稍后重试");} finally {if (prep != null) {try {prep.close();} catch (SQLException e) {}}if (conn != null) {try {conn.close();} catch (SQLException e) {}}}}}
PS:更多更多内容……,请查看 -->《Server 开发》
PS:更多更多内容……,请查看 -->《Server 开发》
PS:更多更多内容……,请查看 -->《Server 开发》