在 java 的 mysql 数据库中插入时间
Inserting a time into mysql database in java
我想将从文本框获取的时间插入到 mysql 数据库 TIME 列。我想我需要将字符串转换为 TIME,就像在查询中使用 "STR_TO_DATE" 将字符串转换为 mysql 中的日期一样。我寻找答案,但没有得到我需要的答案。
编辑: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 接受像“05:12:59”这样的简单字符串到 TIME 类型的列中,但让我们尝试对它有另一个答案。检查从文本框中获取的日期格式并编辑简单日期格式。您可以在下面尝试。
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
您还可以选择设置 stime 并使用其相对 getter.
在查询中传递它
我想将从文本框获取的时间插入到 mysql 数据库 TIME 列。我想我需要将字符串转换为 TIME,就像在查询中使用 "STR_TO_DATE" 将字符串转换为 mysql 中的日期一样。我寻找答案,但没有得到我需要的答案。
编辑: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 接受像“05:12:59”这样的简单字符串到 TIME 类型的列中,但让我们尝试对它有另一个答案。检查从文本框中获取的日期格式并编辑简单日期格式。您可以在下面尝试。
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
您还可以选择设置 stime 并使用其相对 getter.
在查询中传递它