Stacked Q&A

update database with jsp
  • 3 voting
  • 2022-05-25 00:00

    I try to update table in mysql database from jsp using this method:

    <form >
    <input class="form-control" id="ex1" type="text" name="bt2">
    <input type="submit" value="Skicka Tips" onclick="a()">
    </form>
    
    <script> function a(){
    try
    {
      // create a java mysql database connection
      String myDriver = "com.mysql.jdbc.Driver";
      String myUrl = "jdbc:mysql://localhost:3306/studentEnrollment";
      Class.forName(myDriver);
      Connection conn = DriverManager.getConnection(myUrl, "root", "12");
    
      // create the java mysql update preparedstatement
      String query = "update etudiants set dv_o_math = ? where first_name = ?";
      PreparedStatement preparedStmt = conn.prepareStatement(query);
      preparedStmt.setInt(1, 15);
      preparedStmt.setString(2,request.getParameter("bt2"));
    
      // execute the java preparedstatement
      preparedStmt.executeUpdate();
    
      conn.close();
    }catch (Exception )
    { }
    
    }
    

    but still not working .how can I fix the code to get result.

    Rq: I did import java.sql.*

  • 1 1438 0 0
첨부 파일
답변
총 1개의 답변이있습니다.
  • 답변일: 2022-05-25 00:00

    The code written inside a tag is executed by the browser on the client machine Eg: JavaScript code to perform client side validations. To connect to the database , the code must be executed on the server and not on the client machine for which you are using JSP which is a server side scripting language.

    Use scriptlets tags <%%> to write the code that has to be executed on the server before the webpage is sent to the client machine/browser.

    Seems like you are a beginner in JSP. Would recommend you to go through some of the online JSP and Servlet Tutorials.

    For now , try using the below code : a.html

    <form action="FetchData.jsp">
    <input class="form-control" id="ex1" type="text" name="bt2" >
    <input type="submit" value="Skicka Tips">
    </form>
    

    FetchData.jsp

    <%@ page import="java.sql.*" %>
    <%
    try
    {
      // create a java mysql database connection
      String myDriver = "com.mysql.jdbc.Driver";
      String myUrl = "jdbc:mysql://localhost:3306/studentEnrollment";
      Class.forName(myDriver);
      Connection conn = DriverManager.getConnection(myUrl, "root", "12");
    
      // create the java mysql update preparedstatement
      String query = "update etudiants set dv_o_math = ? where first_name = ?";
      PreparedStatement preparedStmt = conn.prepareStatement(query);
      preparedStmt.setInt(1, 15);
      preparedStmt.setString(2,request.getParameter("bt2"));
    
      // execute the java preparedstatement
      preparedStmt.executeUpdate();
    
      conn.close();
    }catch (Exception e){ }
    
    %>
    <h3> The data is successfully updated</h3>
    
  • 0 0 채택된 답변 퍼블 채택!
Tages
    활동순위
    유저
      파트너사