Inserting a time into mysql database in java

空扰寡人 提交于 2019-12-13 19:30:24

问题


I want to insert a time which is taken from a textbox to the mysql database TIME column. I suppose I need to convert String to TIME like converting String to Date in mysql using "STR_TO_DATE" in the query. I looked for answers but I didn't get the answer I required.

Edit: SQL from comments:

"insert into schedules (
    courseid, 
    batch, 
    subjectid, 
    teacherid, 
    stime, 
    etime, 
    date, 
    location, 
    building, 
    department, 
    hall, 
    status
) values ('" + 
    getCourse() + "','" + 
    getBatch() + "', '" + 
    getSubject() + "','" + 
    getTeacher() + "', '" + 
    getStime()+ "','" + 
    getEtime()+ 
    "',STR_TO_DATE('" + getDate() + "','%d-%m-%Y'),'" + 
    getLocation() + "', '" + 
    getBuilding() + "', '" + 
    getDepartment()+ "', '" + 
    getHall() + 
    "','ACTIVE')"

回答1:


As stated in comments Mysql accepts simple strings like '05:12:59' into TIME type columns but lets try to have another answer to it to. Check the format of date you get from textbox and edit Simple date format. You can try below.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parsedDate = dateFormat.parse(request.getParameter("textBoxName"));
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());//or you can assign this stuff to stime variable

I assume you are using preparedStatement as I think you will inserting many times. If so you can set the parameter like this.

preparedStatement.setTimestamp(1, timestamp);//1 is the index of parameter you can choose named parameters too

Also you can choose the to set stime and pass it in query using its relative getter.



来源:https://stackoverflow.com/questions/31096248/inserting-a-time-into-mysql-database-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!