java JDBC-插入時間類型

public class Demo7 {
    public static void main(String[] args) {
        Connection conn=null;
        PreparedStatement ps=null;

    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","dyl123");

        ps=conn.prepareStatement("insert into t_user(username,pwd,regTime,lastLoginTime) values(?,?,?,?)");
        ps.setObject(1, "html5");
        ps.setObject(2, "12355");

        //java.sql.Date,顯示年月茹
        //java.sql.Time,顯示時分秒
        //java.sql.Timestamp,顯示年月日時分秒

        //sql.Date()沒有空構造器,須要傳入一個lang類型的數值
        java.sql.Date date=new java.sql.Date(System.currentTimeMillis());
        ps.setDate(3, date);
        //時間戳,能夠穿傳lang類型的數值或具體年月日時分秒
        java.sql.Timestamp stamp=new java.sql.Timestamp(System.currentTimeMillis());
        ps.setTimestamp(4,stamp);

        //插入隨機日期

        ps.execute();

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {

        try {
            if(null!=ps)
            {
                ps.close();
            }
        }catch(SQLException e)
        {
            e.printStackTrace();
        }
        try {
            if(null!=conn)
            {
                conn.close();
            }
        }catch(SQLException e)
        {
            e.printStackTrace();
        }
    }

}
}
相關文章
相關標籤/搜索