Adding data to database doesn't work when done from a JSP page, but does work when done from the java class

70 Views Asked by At

so this is probably a beginner's problem but I'm new to all this and am very confused.

I have a Java Class called User(), which is supposed to add data into the Java DB, and my goal is to get that from user input on a JSP page. When I try calling the addUser() method from the main inside the java class, it works and the data is successfully added into the Java DB table. But the problem appears when I call the exact same method from my JSP page, it doesn't work.

I used the Netbeans Debugger, and what I found was that the method fails on "pstmt.executeUpdate()" in the addUser() method, but why? What's different from the JSP page to the Java Class? Any help is greatly appreciated, thank you.

Just to let you know that calling other methods from the JSP page work perfectly fine, and also that the lines "SQLCon.Connect()" and "pstmt = SQLCon.getConn().prepareStatement(SQL) work perfectly fine", below is my code.

Inside the JSP Page.

<%
User u = new User();
out.println(u.addUser());
%>

Code in the addUser() Method:

 public static boolean addUser() throws SQLException {
    try {
        SQLCon.Connect();

        String SQL = "INSERT INTO USERS"
                + " (id, FirstName, LastName, Email, Username)"
                + " values (?,?,?,?,?)";

        pstmt = SQLCon.getConn().prepareStatement(SQL);

        pstmt.setInt(1, 1); //This is temporary, will make this into pk, not null, and auto increment
        pstmt.setString(2, "first name");
        pstmt.setString(3, "last name");
        pstmt.setString(4, "email");
        pstmt.setString(5, "username");

        pstmt.executeUpdate(); //JUMPS TO THE CATCH HERE

        return true;
    } catch (Exception exc) {
        exc.printStackTrace();
        return false;
    }
}
0

There are 0 best solutions below