在Java中将时间插入mysql数据库 [英] Inserting a time into mysql database in java

查看:405
本文介绍了在Java中将时间插入mysql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想插入一个从文本框到mysql数据库的TIME列的时间.我想我需要将String转换为TIME,就像在查询中使用"STR_TO_DATE"在mysql中将String转换为Date一样.我在寻找答案,但没有得到所需的答案.

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.

注释中的SQL:

"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')"

推荐答案

如注释中所述,Mysql在TIME类型的列中接受诸如'05:12:59'之类的简单字符串,但尝试对其进行其他回答.检查从文本框中获取的日期格式,然后编辑简单日期格式.您可以在下面尝试.

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

我认为您正在使用prepareStatement,因为我认为您将插入多次.如果是这样,您可以像这样设置参数.

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

此外,您还可以选择设置 stime 并使用其相对的getter在查询中传递它.

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

这篇关于在Java中将时间插入mysql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆