Java 而那些不是员工的人——我如何才能确保它在执行时不会出错?
“雇员”应该能够看到数据库中的所有订单。而非员工必须能够根据其用户ID查看自己的订单 问题是我的行政部门犯了错误 错误说明: 变量p可能尚未初始化 例如,如果我给出我的Java 而那些不是员工的人——我如何才能确保它在执行时不会出错?,java,Java,“雇员”应该能够看到数据库中的所有订单。而非员工必须能够根据其用户ID查看自己的订单 问题是我的行政部门犯了错误 错误说明: 变量p可能尚未初始化 例如,如果我给出我的PreparedStatement p=null,它告诉我第一个SQL是“NullPointerException” 作为一个起点,我只使用OrderID,length,width,height,date和shippingDate和shipped您也需要在if块中准备陈述p(就像在else中一样)。像 ArrayList<O
PreparedStatement p=null
,它告诉我第一个SQL是“NullPointerException”
作为一个起点,我只使用
OrderID
,length
,width
,height
,date
和shippingDate
和shipped
您也需要在if
块中准备陈述p
(就像在else
中一样)。像
ArrayList<Order> orders = new ArrayList<>(); // tom collection.
try {
Connection cc = Connector.connection();
String SQL;
PreparedStatement p;
if("employee".equals(user.getRole()))
{
SQL = "SELECT * FROM orders ORDER BY orderId DESC";
}
else
{
SQL = "SELECT * FROM orders WHERE userId = ? ORDER BY orderId DESC";
p = cc.prepareStatement(SQL);
p.setInt(1, user.getId());
}
try(ResultSet rs = p.executeQuery();)
{
while(rs.next())
{
orders.add(new Order(
rs.getInt("orderId"),
user,
rs.getInt("length"),
rs.getInt("width"),
rs.getInt("height"),
rs.getDate("date"),
rs.getDate("shippingDate"),
rs.getBoolean("shipped")));
}
}
return orders;
}
catch(ClassNotFoundException | SQLException ex){
throw new Other(ex.getMessage());
}
public Order(int orderid, User user, int length, int width, int height, Date dt, Date shippingDate, boolean shipped) {
this.OrderId = orderid;
this.user = user;
this.length = length;
this.width = width;
this.height = height;
this.dt = dt;
this.shippingDate = shippingDate;
this.shipped = shipped;
}
PreparedStatement p;
if("employee".equals(user.getRole())) {
SQL = "SELECT * FROM orders ORDER BY orderId DESC";
// Add this...
p = cc.prepareStatement(SQL);
} else {
SQL = "SELECT * FROM orders WHERE userId = ? ORDER BY orderId DESC";
// Just like here
p = cc.prepareStatement(SQL);
p.setInt(1, user.getId());
}