日期:2014-05-16 浏览次数:20478 次
java.sql.Date是java.util.Date的子类,转换时需注意。
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Date;
/**
*
* @author HaoWang
*/
public class DateTest {
public static void main(String[] args) {
// create(4,"wanghao",true,java.sql.Date.valueOf("1987-11-02"),200.3f);
create(4,"wanghao",true,new Date(),200.3f);
read(4);
}
public static void create(int sid, String name, boolean sex, Date birthday, Float money) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = null;
try {
conn = JdbcUtils.getConnection();
sql = "insert into students(sid,name,sex,birthday,money) value (?,?,?,?,?)";
ps = conn.prepareStatement(sql);
ps.setInt(1, sid);
ps.setString(2, name);
ps.setBoolean(3, sex);
ps.setDate(4, new java.sql.Date(birthday.getTime()));
ps.setFloat(5, money);
int i = ps.executeUpdate();
System.out.println("i="+i);
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
JdbcUtils.free(conn, ps, rs);
}
}
public static void read(int sid) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = null;
try {
conn = JdbcUtils.getConnection();
sql = "select birthday from students where sid=?";
ps = conn.prepareStatement(sql);
ps.setInt(1, sid);
rs = ps.executeQuery();
while(rs.next()) {
System.out.println(rs.getObject(1));
}
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
JdbcUtils.free(conn, ps, rs);
}
}
}
?