Java中将时间转化成Timestamp格式,然后插入MySQL的datatime类型

xiaoxiao2021-02-28  50

现将数组转化成格式如yyyy-MM-dd HH:mm:ss的字符串,然后再SimpleDateFormat 格式化成字符串,最后转换成Timestamp类型,就可以成功插入数据库了。

public static String Datetime(int buffer[]){//时间解析函数

String datetime=""; String st="";     for(int i=0;i<=5;i++){ st+=String.format("d", buffer[i]); }     String dt="20"+st;        StringBuffer sb=new StringBuffer().append(dt); datetime=sb.insert(4,"-").insert(7,"-").insert(10," ").insert(13,":").insert(16,":").toString(); return datetime;

}

public static void insertTrainArrival(String id,String date_type, String section_no, String datetime,String train_no){ Connection con = getConnection(); PreparedStatement pstmt = null; try { SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time=df.format(df.parse(datetime)); Timestamp timeStamp=Timestamp.valueOf(time);//时间timeStamp pstmt=con.prepareStatement("inser tinto t_train_arrival_info(ARRIVAL_ID,DATA_TYPE,SECTION_NO,TIME,TRAIN_NO) values(?,?,?,?,?)"); pstmt.setString(1, id);  pstmt.setString(2, date_type);       pstmt.setString(3, section_no);        pstmt.setTimestamp(4,timeStamp );      pstmt.setString(5, train_no);      pstmt.execute(); } catch (Exception e) { e.printStackTrace(); }finally{ try{ if(pstmt != null){ pstmt.close(); pstmt = null; } } catch(Exception e){ e.printStackTrace(); } try{ if(con != null){ con.close(); con = null; } } catch(Exception e){ e.printStackTrace(); } } }

转载请注明原文地址: https://www.6miu.com/read-2620211.html

最新回复(0)