I will introduce how to get the date and time registered in MySQL with java, and how to register the date and time from java to MySQL. See here for how to connect to MySQL. https://qiita.com/QiitaD/items/d605b07e849e3bec0722
Define the date and time with the timestamp method. The column name is "date_time" and the format is "yyyy-MM-dd HH: mm: ss".
String mySql = "select * from table_name"; // SQL statement to get data with date and time
ResultSet rs = stmt.executeQuery (mySql); // SQL execution, get data
while (rs.next()) {
rs.getTimestamp ("date_time"); // Get date and time information from the acquired data
}
Register the current time as an example.
String mySql = "insert into table (date_time) values ('" + getNowDateTime(){ + "')";
stmt.executeUpdate(mySql);
/**
* Get the current date and time in yyyy / MM / dd HH: mm: ss format. <br>
*/
public static String getNowDateTime(){
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = new Date(System.currentTimeMillis());
return df.format(date);
}
See here for how to get the current time. https://qiita.com/zuccyi/items/d9c185588a5628837137
It's not a problem, but there are two points to note for beginners. ① SQL execution statement When fetching data with select, it is executeQuery, but when updating, insert, delete, it is executeUpdate.
② Single quotation It's easy to forget, but in this sample you have to enclose the date and time in'(single quotes).
Please be aware of the above two because I often stumbled when I was a super beginner.
In this article, I introduced an example of how to handle the date and time, but there are other ways to use it because there are various ways to handle the date and time. (Date, LocaleDateTime, etc.) If you change the type, conversion becomes troublesome, so think carefully before using it.
Date and time type https://www.dbonline.jp/mysql/type/index4.html
Difference between timestamp and datetime https://qiita.com/ykawakami/items/2449a24e3b82ff0cbab6
timestamp exception https://ts0818.hatenablog.com/entry/2017/08/11/155011
Recommended Posts