package com.bjsxt;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* preparedStatement对象的使用
* @author tui
*
*/
public class PreparedStatementDemo {
//向departments表插入一条数据
public void insertDepartments(String departmentName,int locationId) {
Connection conn=null;
PreparedStatement ps=null;
try {
conn = JdbcUtil.getConnection();
ps = conn.prepareStatement("insert into departments values(default,?,?)");
ps.setString(1, departmentName);
ps.setInt(2, locationId);
ps.execute();
} catch (Exception e) {
// TODO: handle exception
}finally {
JdbcUtil.closeResource( ps, conn, null);
}
}
//数据更新
public void updateDepartments(int departmentId,String departmentName,int localhostId) {
Connection conn=null;
PreparedStatement ps=null;
try {
conn = JdbcUtil.getConnection();
ps=conn.prepareStatement("update departments set department_name=?,location_id=? where department_id=?");
ps.setString(1, departmentName);
ps.setInt(2, localhostId);
ps.setInt(3, departmentId);
ps.execute();
} catch (Exception e) {
// TODO: handle exception
}finally {
JdbcUtil.closeResource(ps, conn, null);
}
}
//查询数据
public Departments selectDepartmentsById(int departmentId) {
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
Departments dept=null;
try {
conn=JdbcUtil.getConnection();
ps=conn.prepareStatement("select * from departemnts where department_id=?");
ps.setInt(1, departmentId);
rs=ps.executeQuery();
while (rs.next()) {
dept =new Departments();
dept.setDepartmentId(rs.getInt("department_id"));
dept.setDepartmentName(rs.getString("department_name"));
dept.setLocationId(rs.getInt("location_id"));
}
} catch (Exception e) {
// TODO: handle exception
}finally {
JdbcUtil.closeResource(ps, conn, rs);
}
return dept;
}
public static void main(String[] args) {
PreparedStatementDemo demo=new PreparedStatementDemo();
//demo.insertDepartments("人力资源10", 10);
//demo.updateDepartments(9, "人力资源20", 20);
Departments dept=demo.selectDepartmentsById(10);
if (dept!=null) {
System.out.println(dept.getDepartmentId()+" "+dept.getDepartmentName()+" "+dept.getLocationId());
}
}
}
老师,为什么查询数据selectDepartmentsById这个方法测试报空指针异常(主方法里把if条件删了报空指针异常)