简体   繁体   中英

Error adding date into mysql database from jsp/servlet

I have a 'time' column in my database. I am taking the value to be added from a form on my jsp. The element with time is a dropdown.

The query for adding runs fine but the value in database is being displayed as '00:00:02' for every dropdown selection.

JSP:

Name: <input type="text" name="name">
Select your appointment: <select name="time">
        <option value="1">08:30:00</option>
        <option value="2">09:15:00</option>
        <option value="3">12:30:00</option>
        <option value="4">03:20:00</option>
        <option value="5">05:40:00</option>
           </select>

Servlet:

String time = request.getParameter("time");
String addQuery = "insert into booking (name, time) values (?, ?)";         
pstmt = connection.prepareStatement(addQuery);
pstmt.setString(1, name);
pstmt.setString(2, time);
pstmt.execute();

TestUser 00:00:02 <---- This is the output in DB.

The console is showing "The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature." for Servlet.

From your coding in jsp, the value pass is not the time but 1/2/3/4

instead of doing like this:

Select your appointment: <select name="time">
        <option value="1">08:30:00</option>
        <option value="2">09:15:00</option>
        <option value="3">12:30:00</option>
        <option value="4">03:20:00</option>
        <option value="5">05:40:00</option>
           </select>

try doing like this:

Select your appointment: <select name="time">
        <option value="08:30:00">08:30:00</option>
        <option value="09:15:00">09:15:00</option>
        <option value="12:30:00">12:30:00</option>
        <option value="03:20:00">03:20:00</option>
        <option value="05:40:00">05:40:00</option>
           </select>

plus, is your column type in db is varchar or time?

updated

at your servlet,

String time = request.getParameter("time");
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date;
Time t;

try{
      date = dateFormat.parse(time);
      t = new java.sql.Time(date.getTime());
   }
catch(Exception e){e.printStackTrace();}

String addQuery = "insert into booking (name, time) values (?, ?)";         
pstmt = connection.prepareStatement(addQuery);
pstmt.setString(1, name);
pstmt.setTime(2, t);
pstmt.execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM