Ahmed Helali Ahmed Helali - 7 months ago 27
SQL Question

update database with jsp

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.*

Answer

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>
Comments