邪门的
空指针问题,希望有人能指点,在线等哥哥解决。
困扰了我1上午了,单元测试的时候出现的空指针在实例中取值id的时候取不到。但是在result.next()的时候有啊。。
下面是我DaoImpl里的代码
[code=Java][/code]package com.test.daoImpl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;
import com.test.bean.Employee;
import com.test.dao.EmployeeDao;
public class EmployeeDaoImpl implements EmployeeDao {
private static String ConnectionUrl = "jdbc:oracle:thin:@localhost:1521:TEST";
private static String username = "system";
private static String password = "system";
Connection con = null;
PreparedStatement pre = null;
ResultSet result = null;
public int add(Employee emp) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(ConnectionUrl,username,password);
Statement str = con.createStatement();
result=str.executeQuery("select S_EXTJS.nextval as id from dual");
if(result.next()){
emp.setId(result.getInt("id"));
System.out.println(result.getInt("id"));
System.out.println("emp.getID=="+emp.getId());//这里有值
}
con.prepareStatement("insert into EXTJS(id,username,password,email,brondate,intro) values(?,?,?,?,?,?)");
pre.setInt(1, emp.getId()); //这里报空指针 pre.setString(2,emp.getUsername());
pre.setString(3, emp.getPassword());
pre.setString(4, emp.getEmail());
pre.setDate(5, new java.sql.Date(emp.getBrondate().getTime()));
pre.setString(6,emp.getIntro());
int num = pre.executeUpdate();
System.out.println("执行是否成功?=="+num);
if(num>0){
System.out.println("执行成功");
int newId = 0;
emp.setId(newId);
}
con.commit();
}catch(Exception error){
error.printStackTrace();
try{
con.rollback();
}catch(Exception errors){
errors.printStackTrace();
}
}finally{
try{
if(result!=null){
result.close();
}
}catch(Exception error){
error.printStackTrace();
}finally{
try{
if(pre!=null)
pre.close();
if(con!=null)
con.close();
System.out.println("close connection====");
}catch(Exception error){
error.printStackTrace();
}
}
}
return emp.getId();
}
}
下面是我写的bean set get 是Eclipse生成的没问题的
package com.test.bean;
import java.util.Date;
public class Employee {
private int id;
private String username;
private String password;
private String email;
private Date brondate;
private String intro;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public Date getBrondate() {
return brondate;
}
public void setBrondate(Date brondate) {
this.brondate