有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中向mysql数据库中插入时间

我想在mysql数据库的时间列中插入一个从文本框中提取的时间。我想我需要将字符串转换为时间,就像在mysql中使用查询中的“STR_to_Date”将字符串转换为日期一样。我寻找答案,但没有得到我需要的答案

编辑:来自评论的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')"

共 (1) 个答案

  1. # 1 楼答案

    正如在注释中所述,Mysql接受像'05:12:59'这样的简单字符串进入时间类型列,但让我们尝试对其给出另一个答案。检查从文本框中获取的日期格式,然后编辑简单的日期格式。你可以在下面试试

    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
    

    我假设你使用的是preparedStatement,因为我认为你会多次插入。如果是这样,可以这样设置参数

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

    您还可以选择设置时间并使用其相对getter在查询中传递它