package ch14;
import java.text.SimpleDateFormat;
import java.sql.*;
import java.sql.Date;
public class sqlTest {
/**
 * @param args
 */
public static void main (String args[]){
Connection con=null;
String  username="root";
String password="root";
String url="jdbc:mysql://localhost/test";
Statement stmt = null;
String sql=null;

try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
System.out.print("加载时出现异常 ");
}
 try{
 con = DriverManager.getConnection(url,username,password);
 stmt=con.createStatement();
 sql="select * from student";
 ResultSet rs = stmt.executeQuery(sql);
 
 while(rs.next()){
 Date pd = rs.getDate("pdat");
 SimpleDateFormat ssf= new SimpleDateFormat("yyyy年MM月dd日");
 System.out.println(ssf.format(pd));
 
 }
 
 stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
finally {
try{
if (con==null)con.close();
}catch(SQLException e)
{System.out.print("关闭时出现错误");
}
}
}
}
****************************
 System.out.println(ssf.format(pd));这一句话老异常...望高手指点....
Exception in thread "main" java.lang.NullPointerException
at java.util.Calendar.setTime(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.SimpleDateFormat.format(Unknown Source)
at java.text.DateFormat.format(Unknown Source)
at ch14.sqlTest.main(sqlTest.java:36)

解决方案 »

  1.   

    Unknown   Source 
    ***从数据库取出来的是java.util.Date对象么?如果你是保存Date对象到数据库,必然得通过readObject取反序列化,如果不是Date对象就得:
     long longDate = rs.getLong("xxx");
     Date dt = new Date(longDate);
     String nowString = ssf.format(dt);
      

  2.   

    log一下rs.getDate("pdat")是否有值.抛的空指针异常!