Servlet中利用JDBC操作資料庫,往emp表中添加資料

來源:互聯網
上載者:User

第一步:首先進入資料庫,建庫,建表。

第二步:在myeclipse中建立一個web工程,我的就為web01_demo,接著在WebRoot下建立一個add.jsp檔案。

add.jsp的代碼十分簡單:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>My JSP 'add.jsp' starting page</title>  </head>    <body>   <form action="add">   <h4>add employee</h4>   name:<input type="text" name="name"><br>   salary:<input type="text" name="salary"><br>   <input type="submit" value="confirm">   </form>  </body></html>

第三步:寫提供服務的Servlet,這裡為AddEmployeeServlet,採取繼承HttpServlet的方式,在web.xml檔案中映射的url為add。

AddEmployeeServlet的代碼如下:

public class AddEmployeeServlet extends HttpServlet {private static final String URL="jdbc:mysql://localhost:3306/exercise";private static final String USER="root";private static final String PASS="mysqladmin";public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException {String name=request.getParameter("name");String salary=request.getParameter("salary");Connection conn=null;PreparedStatement pstmt=null;try {Class.forName("com.mysql.jdbc.Driver");conn=DriverManager.getConnection(URL,USER,PASS);pstmt=conn.prepareStatement("insert into emp(name,salary) values(?,?)");pstmt.setString(1,name);pstmt.setDouble(2,Double.parseDouble(salary));pstmt.executeUpdate();PrintWriter pw=response.getWriter();pw.print("<h3>add success</h3>");} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{try {pstmt.close();} catch (SQLException e) {e.printStackTrace();}try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}}

第四步:在myeclipse中部署應用web01_demo,接著啟動Tomcat伺服器。

在瀏覽器裡輸入:http://localhost:8080/web01_demo/add.jsp

瀏覽器返回頁面,在表單中輸入姓名和薪水,點擊confirm按鈕,提交,即可將資料寫入exercise資料庫的emp表。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.