Servlet中如何进行 数据库操作呢?
下文是笔者讲述的使用JDBC的方式对MySQL的操作示例,如下所示:
操作数据库前的准备工作: 在我们准备操作数据库前,我们必须准备一个Java MySQL的驱动程序,并将其添加到Tomcat的lib目录 (采用此种方式,可避免调试时,出现Not Found Class现象) 如: mysql-connector-java-8.0.25.jar 在动态Web项目中引入此jar包,然后编写相应的Servlet代码,即可操作数据库, 那么下文将采用示例的方式展示 Servlet对MySQL数据库的操作示例
/*准备工作*/ 准备jar 包 创建MySQL数据表 D:\PHP\phpstudy_pro\Extensions\MySQL5.7.26\bin>mysql -u root -p Enter password: ********** Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 4 Server version: 5.7.26 MySQL Community Server (GPL) Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | javatest | | mysql | | performance_schema | | sys | +--------------------+ 5 rows in set (0.00 sec) mysql> use javatest; mysql> show tables; +--------------------+ | Tables_in_javatest | +--------------------+ | test | +--------------------+ 1 row in set (0.00 sec) mysql> truncate table test;drop table test; Query OK, 0 rows affected (0.01 sec) Query OK, 0 rows affected (0.01 sec) mysql> show tables; Empty set (0.00 sec) mysql> create table `test` (keyid int ,name nvarchar(60)); Query OK, 0 rows affected (0.03 sec) /*编写数据提交页面 mySqlAddTest.html */ <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Java265.com --Servlet数据插入</title> </head> <body> <form action="/servlet01/servletMySQL" method="POST"> keyId: <input type="text" name ="keyId" /> <br /><br /> name: <input type="text" name ="name" /> <br /> <br /> <input type="submit" value="submit" /> </form> </body> </html> /*编写Servlet处理页面 servletMySQLTest.java */ package servlet01; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/servletMySQL") public class servletMySQLTest extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Connection conn = null; PreparedStatement stmt = null; resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); String title = "Servlet Mysql 数据获取-java265.com"; out.println("<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h3>" + title + "</h3>\n"); try { // 注册 JDBC 驱动器 Class.forName(Jdbc_Driver); // 打开一个连接 conn = DriverManager.getConnection(Dburl, UserName, PassWord); // 执行 SQL 查询 String sql; sql = "select keyId,name from `test`"; stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next()) { // 通过字段检索 int keyId = rs.getInt("keyId"); String name = rs.getString("name"); // 输出数据 out.println("ID: " + keyId); out.println(", 站点名称: " + name); out.println("<br />"); } out.println("</body></html>"); // 完成后关闭 rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { // 处理 JDBC 错误 se.printStackTrace(); } catch (Exception e) { // 处理 Class.forName 错误 e.printStackTrace(); } finally { // 最后是用于关闭资源的块 try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取参数 String keyId = req.getParameter("keyId"); String name = req.getParameter("name"); // 数据插入 dataInsert(Integer.valueOf(keyId).intValue(), name); doGet(req, resp); } static final String Jdbc_Driver = "com.mysql.cj.jdbc.Driver"; static final String Dburl = "jdbc:mysql://localhost:3306/javatest"; // 数据库的用户名与密码,需要根据自己的设置 static final String UserName = "root"; static final String PassWord = "root123456"; private void dataInsert(int keyId, String Name) { Connection conn = null; PreparedStatement stmt = null; try { // 注册 JDBC 驱动器 Class.forName(Jdbc_Driver); // 打开一个连接 conn = DriverManager.getConnection(Dburl, UserName, PassWord); // 执行 SQL 查询 String sql; sql = "insert into `test`(keyId,name)value(?,?)"; stmt = conn.prepareStatement(sql); // 传入参数 stmt.setInt(1, keyId); stmt.setString(2, Name); stmt.executeUpdate(); stmt.close(); conn.close(); } catch (SQLException se) { // 处理 JDBC 错误 se.printStackTrace(); } catch (Exception e) { // 处理 Class.forName 错误 e.printStackTrace(); } finally { // 最后是用于关闭资源的块 try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。