JDBC 關於Date格式

劍握在手發表於2013-12-05

package test;

import java.sql.Connection;
import java.util.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SqlDate {

    /**
     * @param args
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        // TODO Auto-generated method stub
        create("name2",new Date(),1000.9f);
        System.out.println(getData(1));
    }

 

 

    static void create(String name,Date birthday,float money) throws SQLException {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try {
            conn = JdbcUtils.getConnection();
            //3,Statement用於“運送”sql語句和sql語句執行結果
            String sql = "insert into user(name,birthday,money) values (?,?,?)";

            st = conn.prepareStatement(sql);
           
            st.setString(1, name);
            st.setDate(2, new java.sql.Date(birthday.getTime()));//將util的Date轉換為sql的Date
            st.setFloat(3, money);
            //4,執行sql
            int count = st.executeUpdate();

            System.out.println(count);


        } finally {
            JdbcUtils.free(rs, st, conn);
        }
    }
   
   
    private static Date getData(int id) throws ClassNotFoundException, SQLException {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        Date bithday = null;
        try {
            conn = JdbcUtils.getConnection();

            st = conn.createStatement();
           
            rs = st.executeQuery("select birthday from user where id = "+id);
           
            while(rs.next()) {
                bithday = rs.getDate("birthday");
            }
        } finally {
            JdbcUtils.free(rs, st, conn);
        }
       
        return bithday;
    }
   
}

相關文章