1. 程式人生 > >10.3(Java學習筆記)JDBC時間操作

10.3(Java學習筆記)JDBC時間操作

一、時間分類

  資料庫     java類            

  Date  ---- java.sql.Date   表示日期 yyyy-MM--dd (年月日)

  Time  ----java.sql.Time    表示時間 hh--mm--ss(時分秒)

  Timestamp ---- java.sql.Timestamp  表示日期+時間  yyyy--MM--dd hh--mm-ss(年月日時分秒)

  

 

  接下來我們重新建立一個test_date表,其中欄位名稱及型別如上圖所示。

  建表語句:

CREATE TABLE `test_date` (
  `date` date DEFAULT NULL,
  `time` time DEFAULT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  

import java.sql.Connection;
import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestJDBC{ public static void main(String[] args){ final String connectionUrl = "jdbc:mysql://localhost:3306/mybatis"; String userName
= "root"; String passWord = "123456"; Connection conn = null; PreparedStatement ps = null;
     //建立對應時間物件,資料庫插入物件時java.sql包下的,
     //為了防止和java.util包下的時間類混淆,所以這裡寫了完整的路徑。
java.sql.Date date
= new java.sql.Date(System.currentTimeMillis()); java.sql.Time time = new java.sql.Time(System.currentTimeMillis()); java.sql.Timestamp timestamp = new java.sql.Timestamp(System.currentTimeMillis()); try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(connectionUrl,userName,passWord); conn.setAutoCommit(false); ps = conn.prepareStatement("INSERT INTO `mybatis`.`test_date`" + "(`date`, `time`, `timestamp`) " + "VALUES (?, ?, ?);"); ps.setObject(1, date);//設定時間(年月日) ps.setObject(2, time);//時分秒 ps.setObject(3, timestamp);//年月日時分秒 ps.execute(); conn.commit(); System.out.println("insert 成功"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // TODO Auto-generated catch block e.printStackTrace(); } } }
執行結果:
insert 成功

 

 

二、查詢資料庫中指定時間段的資料

  首先我們建立一個新表test_select_timestamp, 表字段名稱及型別如下圖所示。

  

  建表語句:

CREATE TABLE `test_select_timestamp` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tusername` varchar(255) DEFAULT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18001 DEFAULT CHARSET=utf8;

 

 1.在資料庫中插入一些資料(日期採用隨機生成)

  2.輸入查詢區間

  3.執行對應SQL語句,返回結果集

  4.遍歷結果集

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import com.mysql.cj.protocol.Resultset;

public class TestJDBC{
    public static void main(String[] args){
        final String connectionUrl = "jdbc:mysql://localhost:3306/mybatis";
        String userName = "root";
        String passWord = "123456";
        Connection conn = null;
        PreparedStatement ps = null;
        
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(connectionUrl,userName,passWord);
            conn.setAutoCommit(false);
            ps = conn.prepareStatement("INSERT INTO `mybatis`.`test_select_timestamp`"
                    + "(`tusername`, `timestamp`) "
                    + "VALUES ( ?, ?);");
            //隨機插入資料,   語句物件,插入條數
            randomInsertTime(ps,2000);//隨機插入2000條不同的時間資料
            //根據指定時間區間查詢內容
            ResultSet rs = findSpecifyTime(conn,"2019-1-11 00-00-00","2019-1-11 20-00-00");
            conn.commit();
            //輸出結果集
            while(rs.next()){
                System.out.println(rs.getInt(1) +"--" + rs.getString(2) + "--" + rs.getTimestamp(3));
            }
            System.out.println("select 成功");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            try {
                conn.rollback();
            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //插入dateNum條資料,日期隨機
    public static void randomInsertTime(PreparedStatement ps,int dateNum) throws SQLException{
        for (int i = 0; i <dateNum;i++){
            long randTime = (long)(Math.random()*100000000);
       //系統獲取當前時間減去一個隨機數 java.sql.Timestamp timestamp
= new java.sql.Timestamp(System.currentTimeMillis()-randTime); ps.setObject(1, "hcf"+i); ps.setObject(2, timestamp); ps.execute(); } } //將yyyy-MM-dd hh-mm-ss格式的字串轉為代表對應時間物件的long型資料 public static long stringToDateLong(String ts){ DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss"); try { return df.parse(ts).getTime(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return 0;//異常返回0 } } //尋找時間在start-end之間的資料,返回查詢結果集 public static ResultSet findSpecifyTime(Connection conn,String start,String end) throws SQLException{ PreparedStatement ps = conn.prepareStatement("select * from test_select_timestamp " + "where timestamp >? and timestamp<?");
     //根據字串轉換成的long型資料,構造Timestamp物件,設定查詢引數 ps.setObject(
1, new java.sql.Timestamp(stringToDateLong(start))); ps.setObject(2, new java.sql.Timestamp(stringToDateLong(end))); ResultSet rs = ps.executeQuery(); conn.commit(); return rs; } } 
執行結果:
16001--hcf0--2019-01-11 16:26:28.0
16004--hcf3--2019-01-11 11:31:46.0
16006--hcf5--2019-01-11 15:45:16.0
16008--hcf7--2019-01-11 17:12:24.0
                 .
                 .
                 .//後面還有很多資料就不一一列出了
select 成功

 

上述程式碼先插入指定條資料,接著輸入查詢時間區間的字串形式,之後將字串轉換為對應時間物件所代表的long型資料。

然後將這個long型資料作為構造Timestamp物件的引數,最後根據Timestamp物件和SQL語句在資料庫中查詢並得到結果集。