向mysql中插入Date類型的資料

來源:互聯網
上載者:User

標籤:

先看資料庫表的定義

date欄位為sql.date類型。我要向其中插入指定的日期和當前日期。

一、插入當前日期

思路:先擷取當前系統,在將當前系統時間轉換成sql類型的時間,然後插入資料庫。代碼如下

public static void insert_now() throws ClassNotFoundException, SQLException{    java.util.Date utilDate = new Date();                                    //擷取java.util.Date對象---也即目前時間    java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());    //將java.util.Date類型轉換成java.sal.Date類型    Connection conn = JDBCUtils.getConn();                        //擷取資料庫連接    String sql = "insert into testdate(date) values (?)";    PreparedStatement ps = conn.prepareStatement(sql);    ps.setDate(1, sqlDate);                                        //sql類型的資料插入資料庫    ps.executeUpdate();    conn.close();}

資料庫重新整理後如下:

二、插入指定日期的資料

將"2012-12-21"這個字串插入資料庫。思路:使用java.sql.Date.valueOf(String str)方法將字串轉換成sql類型的Date,然後插入資料庫中

public static void string_insert_sql() throws ClassNotFoundException, SQLException{    String str = "2012-12-21";    java.sql.Date sqlDate = java.sql.Date.valueOf(str);        //將字串轉換成sql.Date類型    Connection conn = JDBCUtils.getConn();                    //串連資料庫    String sql = "insert into testdate(date) values (?)";    PreparedStatement ps = conn.prepareStatement(sql);    ps.setDate(1, sqlDate);                                    //sql類型的額資料插入資料庫    ps.executeUpdate();    conn.close();}

資料庫重新整理後如下:

三、從資料庫中讀Date類型的資料

public static void sql_to_string() throws ClassNotFoundException, SQLException{    Date date = null;    Connection conn = JDBCUtils.getConn();                    //擷取資料庫連接    String sql = "select * from testdate where id = 4";    PreparedStatement ps = conn.prepareStatement(sql);    ResultSet rs = ps.executeQuery();    if(rs.next()){        date = rs.getDate(2);    }    conn.close();    System.out.println(date);                                //可以將date轉換成date.toString()        }

附上一片看到的博文  http://blog.csdn.net/foamflower/article/details/2171537

向mysql中插入Date類型的資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.