Java update query experiencing issues

This servlet is designed to add a new user entry into a database table.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String firstname = request.getParameter("firstname");
    String lastname = request.getParameter("lastname");
    String dob = request.getParameter("dob");
    String gen = request.getParameter("gen");
    String mem_type = request.getParameter("mem");
    String fname = request.getParameter("fname");
    String addr = request.getParameter("addr");
    long number = Long.parseLong(request.getParameter("c_no"));
    String loginID = request.getParameter("loginID");
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    java.sql.Date sqlDate = null;
    SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
    try {
        Date dobb = sdf.parse(dob);
        sqlDate = new java.sql.Date(dobb.getDate());
    }
    catch(ParseException e) {
        e.printStackTrace();
    }

    String name = firstname+" "+lastname;

    Connection conn = null;

    PrintWriter out = response.getWriter();

    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost/library", "root", "asdfghjkl");

        PreparedStatement updatequery = (PreparedStatement)conn.prepareStatement("INSERT INTO librarian(Librarian Name,Gender,Address,Date Of Birth,Login ID,Contact Number) VALUES (?,?,?,?,?,?)");

        updatequery.setString(1, name);
        updatequery.setString(2, gen);
        updatequery.setString(3, addr);
        updatequery.setDate(4, sqlDate);
        updatequery.setString(5, loginID);
        updatequery.setLong(6, number);

        int i = updatequery.executeUpdate();

        out.println(i+"Inserted.");

        conn.close();

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

I've implemented the above code in an attempt to insert a new record into a table, but it's not functioning as expected. Any assistance in identifying errors within my program would be greatly appreciated.

The following JSP code snippet is provided :

<html>
<head>
<style>
#d1{
position:relative;
bottom:0    

}

</style>

</head>

<jsp:include page="header.html"/>

<body>
<div>
<form class="page" method="post" action="RegisterPage">

First Name : <input name="firstname">

<br><br>

Last Name : <input name="lastname">

<br><br>

Date of Birth : <input name="dob" type="date">

<br><br>

Gender : 
<input type="radio" name="gen" value="Male">Male 
<input type="radio" name="gen" value="Female">Female 

<br><br>

Membership Type :
<input type="radio" name="mem" value="Librarian">Librarian
<input type="radio" name="mem" value="Member">Member

<br><br>

Father's Name : <input name="fname">

<br><br>    

Address <input name="addr">

<br><br>

Contact Number : <input name="c_no" type="text">

<br><br>

Email ID : <input name="loginID" type="email">

<br><br>

Username : <input name="username">

<br><br>

Password : <input name="password" type="password">

<br><br>

<input type="submit" value="Register">

</form>
</div>
</body>
<div id="d1">
<jsp:include page="footer.html"/>
</div>
</html>

The table consists of 7 columns, with the first being an auto-increment primary key and the rest comprising standard columns for Name, Gender, Address, Date of Birth, Login ID, and Contact Number.

An error message is displayed in the console: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'login table(Login ID,Username,Password) VALUES ('[email protected]','asdfghjkl','asdfg' at line 1

Answer №1

Instead of using your line, you can try this:

Create a PreparedStatement object named updateQuery and set it to the connection.prepareStatement("INSERT INTO librarian(Name,gender,address,Date_of_birth,login_ID,contact_number) VALUES (?,?,?,?,?,?)");

Always keep in mind that when you have an auto_increment field in your table, you need to specify the column names while inserting data into the table.

Double check your setString() method, for loginID & number, it should be setInt()

Now, let's talk about the Date. The date received from the JSP page will be in java.Util format, but for updating/inserting into the database, it needs to be in java.sql.Date format. So, make the following conversion:

String dateOfBirth = request.getParameter("dob");  
        java.sql.Date sqlDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        try {
            Date dob = sdf.parse(dateOfBirth);   
            sqlDate = new java.sql.Date(dob.getDate());  
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

Finally, insert/update the database using:

updateQuery.setDate(4, sqlDate);

Thank you

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CodeIgniter - Filter MySQL records by date

Currently, I am utilizing CodeIgniter's MVC framework to retrieve my records within a specified time frame. I have successfully implemented filtering for a dropdown and achieved the desired outcome. However, I am struggling to replicate this functiona ...

JavaScript in Internet Explorer is showing an error message stating that it is unable to access the property '0' of an undefined or null

JavaScript Code function update() { var newAmt = 0; var newtable = document.getElementById("tbl"); for ( var i = 0; i < newtable.rows.length; i++) { innerTable = newtable.rows[i].cells[0].childNodes[0]; if ( (innerT ...

Determine the overall cost based on varying percentage increases for each step

I am currently working on developing a price estimation calculator. Here is the breakdown: For 1000 MTU, the price will be 0.035, resulting in a total of 35. For 2000 MTU, the price will be 0.034, making the total 67. For 3000 MTU, the price will be 0.03 ...

Generating a success message popup using jquery and PHP

Is there a way to create a more visually appealing popup box success message using jQuery and PHP without using ajax? I typically rely on just javascript. <?php $query = //my query insert query if($query){ echo "<script>alert('su ...

Troubles with retrieving Array data for a JavaScript column chart

I am currently developing a Flask app in Python and utilizing render_template to send back 2 arrays, "names" and "deals", to my HTML file. I have confirmed that these arrays are working correctly based on the code snippet below that I tested, which display ...

Receive notifications when there are modifications in the JSON data using AJAX and jQuery

Below is the code snippet I created: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Sample JSON Data Update</title> </head> <body> <style> span { font ...

Press the HTML link to interact with a text using JAVA

I am currently working on creating a class that is able to interact with an A text/button in HTML. The webpage requires a username and password, so I have utilized JSOUP to parse the document and insert the user and password details using the .data method: ...

In the IE7 standards mode, table cells with no content will have a height of 1px

When utilizing IE7 standards mode within IE9, empty table cells are automatically assigned a height of 1px. As a result, elements positioned beneath the table appear lower on the page than intended. To view an example of this issue, refer to the code provi ...

When the bootstrap 5 dropdown is activated, flex wrap functionality triggers vertical scrolling

Every time I click on the dropdown, it causes a vertical scroll instead of popping out like a regular dropdown. I want to maintain the horizontal scroll while fixing this issue. Any suggestions on how to solve this problem? Demo: https://jsfiddle.net/d3j ...

Guide to implementing client-side validation in MVC 4 without relying on the model

Currently, I am developing an ASP.NET MVC 4 project where I have decided not to utilize View Models. Instead, I am opting to work with the classes generated from the Entities for my Models. I am curious if there are alternative methods to achieve this. A ...

What is the best way to perform a cross-domain Ajax request to a remote server by utilizing a local PHP file as a

I am facing a challenge where I need to update data in a RDF graph by making a POST call. When I attempt to do this using Ajax in jQuery directly, I receive a console warning stating 'No 'access-control-allowed-origin' ecc.ecc.' However ...

The class styling is malfunctioning

When I click the 'night' button, I want the word color in the class=css to change to white. However, this is not working as intended, even though all other word colors are changing correctly. Here is my code: .css { font-weight: bold; ...

Is it possible to verify if the provided form input variable exists within an array? Can anyone point out any oversights?

Feeling a bit lost here, not sure what I've missed. Any help would be greatly appreciated as my calculations never seem to come out right. function validateZip(){ var zipCode = $("input[name='zipCode']").val(); var redRiverHondaZips = ...

Using AJAX to send data with a POST request in Django may not function properly

Let me preface by saying I have searched for solutions online, but none of them seem to address my specific issue (mainly because they use outdated methods like Jason). I am currently working on a Django project and trying to implement ajax for a particul ...

The visible overflow-x property is failing to display the excess content within the unordered list

Imagine having a complex bootstrap dropdown menu with over 100 li items. Each time you hover over an li, a new dropdown opens next to it. The problem arises when trying to make the list scrollable by setting max-height:300px; overflow-y:scroll; overflow-x ...

Transforming form command objects in Spring MVC using JavaScript or AJAX execution

I'm currently utilizing Spring MVC 3.0 for the development of a web application. Users have the option to retrieve customers by entering their ID, or simply submitting an empty form to display all customers that they can navigate through using button ...

Which option is preferable: List or Collection?

Currently, I am working on managing a collection of data stored in an object. The challenge lies in ensuring that the internal implementation remains hidden from the end user while still providing the user with the ability to modify and access the data. At ...

Using Jquery to generate key value pairs from a form that is submitted dynamically

I'm still learning the ropes of jquery and struggling with a specific issue. I'm looking for a way to dynamically set key:value pairs in the code below based on form inputs that have variable values. The code works when I manually add the key:va ...

How can I use Angular 4 typescript to deactivate a button based on the value of a boolean variable?

I am looking to define a function in TypeScript called 'isActive()', which I will then invoke on a button within my HTML file. Additionally, I have already declared a boolean variable named 'isActive'. In this scenario, I have two butto ...

Options for Ajax in jQuery UI combobox are customizable

I am looking to personalize the dropdown options of the combobox widget created using jQuery UI Autocomplete. The current options are either predetermined from the SELECT tag OPTIONS or sourced from a JSON array. //getter var source = $( ".selector" ).aut ...