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



你可能感兴趣的:(7 Time,Date与Timestamp的区别)