PreparedStatement做用

/*PreparedStatement是Statement的子接口(如圖所示),表示預編譯的 SQL 語句的對象,SQL 語句被預編譯並存儲在PreparedStatement對象中。而後可使用此對象屢次高效地執行該語句。*/   html

String id = request.getParameter("id");                                                                            mysql

String sql = "UPDATE tb_person SET name = ?,english_name = ?,sex = ?,age = ?,birthday = ?,description = ? WHERE id = ? "; //7個問號表明7個字段預先要保留的值 sql

        Connection conn = null;
        PreparedStatement preStmt = null;
        
        try{
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            conn = DriverManager.getConnection(
                                "jdbc:mysql://localhost:3306/databaseWeb?characterEncoding=UTF-8",
                                "root",
                                "admin");
            
            preStmt = conn.prepareStatement(sql);// 使用PreparedStatement對象來構建並執行SQL語句
            preStmt.setString(1, name);//把name設置到SQL中的第1個問號處                                             preStmt.setString(2, englishName);
            preStmt.setString(3, sex);
            preStmt.setInt(4, Integer.parseInt(age));
            preStmt.setDate(5, new Date(new SimpleDateFormat("yyyy-MM-dd").parse(birthday).getTime()));
            preStmt.setString(6, description);
            preStmt.setInt(7, Integer.parseInt(id));
            
            // 使用 preStmt 執行 SQL 語句
            int result = preStmt.executeUpdate(sql);
    
            out.println("<html><style>body{font-size:12px; line-height:25px; }</style><body>");
            
            if(result == 0)        out.println("影響數目爲 0, 修改失敗. ");
            else    out.println(result + " 條記錄被修改。");
            
            out.println("<a href='listPerson.jsp'>返回人員列表</a>");
            
            // 將執行的 SQL 語句輸出到客戶端
            out.println("<br/><br/>執行的 SQL 語句爲:<br/>" + sql);
            
        }catch(SQLException e){
            out.println("執行SQL\"" + sql + "\"時發生異常:" + e.getMessage());
            e.printStackTrace();
        }finally{
            if(preStmt != null)    preStmt.close();
            if(conn != null)    conn.close();
        }
    }jsp

相關文章
相關標籤/搜索