java web 中 JSP增刪改查mySQL資料

來源:互聯網
上載者:User

標籤:

先在workbench中建立一個schema 比如叫 javatemp
再右鍵shcema裡面的table建立一個叫new_table的table
然後設定一下table裡面有什麼

右鍵new_table 顯示前100行 可以先往裡面手動添加一些資料

資料庫的就到這

然後開啟J2EE 建立Dynamic web project
先匯入串連mysql的驅動jar包 直接將jar包拖到WEB-INF下的lib目錄

在webContent裡建立讀取資料庫jsp檔案 代碼如下

<%@page import="java.sql.*"%><%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>JSP讀取資料庫</title></head><body><table border="1" align="center">    <tr>        <th>id</th>        <th>name</th>        <th>author</th>        <th>publishing</th>        <th>price</th>        <th>data</th>    </tr>    <%        String driverClass="com.mysql.jdbc.Driver";        String url = "jdbc:mysql://127.0.0.1/javatemp";        String user = "root";        String password = "1234";        Connection conn;        PreparedStatement pst = null;        try{            Class.forName(driverClass).newInstance();            conn = DriverManager.getConnection(url,user,password);            String sql = "select * from new_table";            Statement stmt = conn.createStatement();            ResultSet rs = stmt.executeQuery(sql);            while(rs.next()){                %>        <tr>            <td><%=rs.getString("id") %></td>            <td><%=rs.getString("bookname") %></td>            <td><%=rs.getString("publishing") %></td>            <td><%=rs.getString("writer") %></td>            <td><%=rs.getString("price") %></td>            <td><%=rs.getString("date") %></td>        </tr>        <%            }        }catch(Exception e){            e.printStackTrace();        }        %></table></body></html>

上面代碼中 user 和 password 是你自己資料庫的使用者名稱和密碼
127.0.0.1也是看你自己資料庫的地址

我的兩個資料庫連接 localhost 和127.0.0.1都一樣
運行到伺服器上會顯示結果

以上就是查詢mySQL的部分

接下來插入新資料
建立InsertDate.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body><form action="./insertDate" method="post">id:        <input type="text" name="id" /><br/>bookname:  <input type="text" name="bookname" /><br/>publishing:<input type="text" name="publishing" /><br/>writer:    <input type="text" name="writer" /><br/>price:     <input type="text" name="price" /><br/>date:      <input type="text" name="date" /><br/><input type="submit" value="submit"/></form></body></html>

其中form的action insertDate是一個servlet 負責插入資料庫資料
建立這個servlet

package servlet;import java.io.IOException;import java.io.PrintWriter;import java.sql.*;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 insertDate */@WebServlet("/insertDate")public class insertDate extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public insertDate() {        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    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        PrintWriter out = response.getWriter();        String id = request.getParameter("id");        String bookname = request.getParameter("bookname");        String publishing = request.getParameter("publishing");        String writer = request.getParameter("writer");        String price = request.getParameter("price");        String date=request.getParameter("date");        String driverClass="com.mysql.jdbc.Driver";        String url = "jdbc:mysql://127.0.0.1/javatemp";        String user = "root";        String password = "1234";        Connection conn;        try {            int i=0;            Class.forName(driverClass).newInstance();            conn = DriverManager.getConnection(url,user,password);            String sql = "insert into new_table (id,bookname,publishing,writer,price,date) "                    + "values(?,?,?,?,?,?)";            Connection conn1 = DriverManager.getConnection(url, user, password);            PreparedStatement pstmt;            pstmt = (PreparedStatement) conn1.prepareStatement(sql);            pstmt.setString(1, id);            pstmt.setString(2, bookname);            pstmt.setString(3, publishing);            pstmt.setString(4, writer);            pstmt.setString(5, price);            pstmt.setString(6, date);            i = pstmt.executeUpdate();            conn1.close();            pstmt.close();        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

運行之後 插入資料注意資料類型 id不能重複 date是DATE類型
格式為 年-月-日

java web 中 JSP增刪改查mySQL資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.