这样,“雇员”应该能够看到数据库中的所有订单。而那些不是雇员的人必须能够根据其userId查看自己的订单。
问题只是我的executeQuery出错了。
错误提示:
变量p可能尚未初始化
例如,如果我输入PreparedStatement p = null
,它会告诉我第一个SQL是“ NullPointerException ”
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;
}
作为起点,我仅使用OrderID
,length
,width
,height
,date
,shippingDate
和{{1 }}。
答案 0 :(得分:0)
您还需要在PrepareStatement p
块中if
(就像在else
中一样)。喜欢,
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());
}