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();
        }
    }

}
}

猜你喜欢

转载自blog.51cto.com/14437184/2440972
今日推荐