7 Time,Date与Timestamp的区别

1: 测试date,time,timestamp
2: 时间操作---日期段和时间段查询

import java.sql.*;
import java.util.Random;
/**
 * 测试date,time,timestamp
 *
 */
public class TestTime {
    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","123456");
            
            for(int i=0;i<1000;i++){
                ps = conn.prepareStatement(
                    "insert into user (name,age,timestamp,date,time) values (?,?,?,?,?)");          
                ps.setObject(1, "王五");
                ps.setObject(2, "14");
                
                int rand = 1000000000 + new Random().nextInt(1111111111);
                
                //Date,插入值为"年-月-日"
                java.sql.Date date = new java.sql.Date(System.currentTimeMillis()-rand);
                ps.setObject(4, date);
                
                //timestamp,插入值为"年-月-日,时:分:秒"
                Timestamp stamp = new Timestamp(System.currentTimeMillis()-rand);
                ps.setTimestamp(3, stamp);
                
                //time插入值为"时:分:秒"
                ps.setTimestamp(5, stamp);  
                ps.execute();
            }
            
            System.out.println("ps插入的用户");
        
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }   
    }
}



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容