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

"Position the input file with Bootstrap's input text for a seamless alignment

After experimenting with the design of my input file using this code snippet, I am facing difficulties aligning the button within the text input of a bootstrap element. Below is the code I have used to style my input field, but unfortunately, the bootstra ...

My Javascript file is not being recognized by MVC

Initially, I created an MVC application without fully understanding that MVC is more backend-oriented than frontend-focused. I ended up building a simple website with just HTML, CSS, and Javascript files, which worked perfectly. However, when I tried to in ...

Tips for Implementing Multi-Level/Nested in Ajax Requests

I am currently developing a user-friendly web application with intuitive multi-level options that loads new content without the need to refresh the entire page. This is how my structure looks: /index.php /schools.html /colleges.html Within schools.html, ...

Is there a way to change the orientation of the cards so that they move from left to right instead of

I am looking to have my cards displayed from left to right rather than vertically, but I'm struggling to achieve this. I have tried using the float: left property with no success. Below is an example of a single card in my layout. They all follow the ...

Position a modal in the vertical center with scroll functionality for handling extensive content

Looking for ways to tweak a Modal's CSS and HTML? Check out the code snippets below: div.backdrop { background-color: rgba(0, 0, 0, 0.4); height: 100%; left: 0; overflow: auto; position: fixed; top: 0; width: 100%; z-index: 2020; } ...

Building an easy-to-use jQuery task list

I'm currently working on a basic to-do list in Javascript, but I've encountered an issue. When I check the checkbox, the style of the adjacent text doesn't change as expected. Instead, it's the heading text that is affected by the chang ...

Unable to retrieve static files

I'm trying to incorporate the Jquery-ui datetime picker into my express js application, but I encountered a 404 error. <p>Date: <input type="text" id="datepick"></p> <link rel="stylesheet" type="text/css" href="stylesheets/jquery ...

Having difficulty retrieving the value of a dynamically selected radio button in AngularJS

Having trouble with selecting radio options in my code, need some assistance to fix it. Check out my Plnkr Code - http://plnkr.co/edit/MNLOxKqrlN5ccaUs5gpT?p=preview Although I am able to retrieve names for the 'classes' object, the selections ...

Open a file using the fs module while ensuring the original file is preserved

I've been working on a NodeJS API that sends emails. Each time I need to send an email, I use the index.handlebars template. To customize the template before sending the email, I utilize the Node File System (fs) module to readFileSync() and then ap ...

Nesting a DIV tag within another DIV tag

Being relatively new to web design, my understanding of the DIV tag is that it serves as a logical container for whatever content is inside, and those elements will be formatted according to its rules. I have an outer DIV tag styled as <div style="margi ...

Application utilizing electron technology featuring various tabbed browsing windows connecting to secure websites

Currently, I am in the process of developing my own unique version of a platform similar to using Electron technology. The objective for this app is to provide users with the ability to view multiple URLs simultaneously, such as and , through a tabbed i ...

Extract value from child div using JQuery and update text in another section of the page

Here is a fiddle showcasing the concept I am working on: https://jsfiddle.net/wvz9p3e7/1/ The code is written in PHP and involves a loop for cycling through 7 or 8 different garments. My goal is to have the window on the right side of the fiddle display t ...

Controlling HTML5 Video Playback with JavaScript: Pausing at Custom Frames

I need to implement a feature in my web application where I can pause an HTML5 video at specific frames using pure JavaScript, not based on minutes. <video id="media-video" controls> <source id="media-source" src="media/video.mp4" typ ...

The browser encountered an issue trying to load a resource from a directory with multiple nested levels

I've stumbled upon an unusual issue. Here is a snapshot from the inspector tools. The browser is unable to load certain resources even though they do exist. When I try to access the URL in another tab, the resource loads successfully. URLs in the i ...

Continuously simulate mousewheel events

I'm trying to make my mousewheel event trigger every time I scroll up, but it's only firing once. Can you assist me with this issue? Please review the code snippet below. $('#foo').bind('mousewheel', function(e){ if(e.o ...

Apply the active class to only one element at a time

Presented here is a table showcasing available dates and times. Users can select a specific time by clicking on the "Choose" link. Currently, when a user selects a time, the class "active" is applied. However, the desired behavior is to remove the previous ...

Is manually coding HTML for email necessary, or are there any practical tools or converters available?

Creating HTML emails is a different challenge compared to designing websites, as it requires working with tables instead of CSS. I'm in need of recommendations for tools specifically designed for HTML email creation, preferably from individuals who h ...

Show or hide a div through two variables that toggle between different states

It's possible that I'm not fully awake, so missing the obvious is a possibility. However, I have 2 variables that determine whether a div has a specific class or not. The class functions more like a toggle; so the following conditions should tri ...

The incorporation of zoom disrupts the smooth scrolling capability of the menu

My landing page has a menu that scrolls users to the selected section. However, my client prefers the page at a 90% zoom level. To accommodate this request, I added the following line of code: body { zoom:90%; } Unfortunately, when I click on a menu o ...

What is preventing this brief code from functioning properly? I am trying to extract a value from an input field and add it to a div element

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script src="//ajax.googleapis.com/ajax/libs/jque ...