使用 JDBC 插入 Timestamp 值

來源:互聯網
上載者:User
        問題描述
        MySQL 資料庫一個簡單的表
CREATE TABLE `client_file` (  `fileId` bigint(20) NOT NULL AUTO_INCREMENT,  `fileName` varchar(260) DEFAULT NULL,  `isFolder` char(1) DEFAULT NULL,  `fileTime` datetime DEFAULT NULL,  PRIMARY KEY (`fileId`) USING BTREE) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

        對於 fileTime 欄位,如果使用 java.sql.PreparedStatement 的 setDate 方法,資料庫會得到類似 '2011-10-26 00:00:00' 的結果,我們想要類似 '2011-10-26 17:12:50' 的記錄。如何使用 JDBC 插入 Timestamp 值。不要使用資料庫函數,如 MySQL sysdate。
        解決辦法
        建立一個返回當前 timestamp 的函數,例如:
private static java.sql.Timestamp getCurrentTimeStamp() { java.util.Date today = new java.util.Date();return new java.sql.Timestamp(today.getTime()); }

        然後通過 preparedStatement.setTimestamp() 設定 timestamp:
String insertTableSQL = "INSERT INTO client_file"+ "(fileName, isFolder, fileTime) VALUES"+ "(?,?,?)";preparedStatement = dbConnection.prepareStatement(insertTableSQL);preparedStatement.setTimestamp(3,getCurrentTimeStamp());

        相關問題
        如果想批量插入一些 client_file 記錄呢。
        可以用 java.sql.PreparedStatement 的 addBatch 依次添加多條記錄:
public void insertClientFile(Connection conn, char from) {Random random = new Random();String sql = "INSERT client_file (fileName, isFolder, fileTime) VALUES(?,?,?)";PreparedStatement prest = null;try {conn.setAutoCommit(false);prest = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);// 每個使用者 5000 個目錄,5000 個檔案for (int x = 0; x < 5000; x++) {long fileTime = System.currentTimeMillis();fileTime += random.nextInt(100000000);// 先加入一個 folderprest.setString(1, this.getFileName(from, random));prest.setString(2, "1");prest.setTimestamp(3, new Timestamp(fileTime));prest.addBatch();// 再加入一個 fileprest.setString(1, this.getFileName(from, random));prest.setString(2, "0");prest.setTimestamp(3, new Timestamp(fileTime + random.nextInt(10000)));prest.addBatch();}prest.executeBatch();prest.close();conn.commit();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}

        參考資料
Insert Timestamp Value In PreparedStatement 三種JDBC批量插入編程方法的比較 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.