【问题标题】:How to eliminate the for loop results from database using java? [closed]如何使用java消除数据库中的for循环结果? [关闭]
【发布时间】:2022-10-18 09:16:28
【问题描述】:

我正在编写一个脚本来生成每个时间表和日期的座位号以及每个住宿的总容量。

| Accommodation   |  Capacity  |
| VIP             |       25   |
| Premium         |      100   |
| Economy         |      150   |

这是我现在表中的数据:

| Booking #      | Fullname    |  Accommodation  |   Seat #  | Trxn Date  |
| 0000001        | Joe Doe     |  VIP            |    001    | 2022-09-13 |

我打算从 for 循环结果中消除当前存储在我的表中的座位号。

这是我尝试过的代码:

String val = request.getParameter("accommodation");int capacity=0;String date = request.getParameter("date");
String sql = "Select Capacity from tblcapacity WHERE Seat_Type=?";
pst = conn.prepareStatement(sql);
pst.setString(1, val);
rs = pst.executeQuery();
if(rs.next())
{
    capacity = rs.getInt("Capacity");
}

for(int x = 1;x<=capacity;x++)
{
    String vals = String.format("%03d", x);
    pst = conn.prepareStatement("Select SeatNumber from tblcustomer WHERE TrxnDate='"+date+"' AND SeatNumber!= '"+vals+"'");
    rs = pst.executeQuery();
    if(rs.next())
    {
        write.print("<option>"+vals+"</option>");
    }
}

它将根据每个住宿的容量生成座位号。如何消除已存储在 tblcustomer 中的现有座位号?

【问题讨论】:

  • 旁注:您不需要为每次迭代调用prepareStatement()。只需创建一次并重复使用。也不要使用"... TrxnDate='"+date+"' ...",因为它容易受到 SQL 注入的影响,因此使用准备好的语句是没有意义的。而是使用"... TrxnDate=?" 等以及pst.setString(correct_parameter_index, date) 等。
  • 至于摆脱座位号:你的意思是你想对每个日期和类型进行count(*) 查询吗?这将导致不需要整个循环,只需执行SELECT Seat_Type, count(*) as num_seats FROM tblcustomer WHERE TrxnDate=? GROUP BY Seat_Type 之类的操作,然后遍历结果以获取该日期每种类型的预留座位数。将这些数字与每种类型的容量进行比较,您就完成了。
  • 根据每个住宿的容量生成座位号,一旦座位号已经存储在 tblcustomer 中,将被淘汰
  • 啊,所以你想得到一个尚未被占用的座位号列表?在那种情况下,我会改变方法:选择全部给定日期和给定类型的座位号(您的查询也将获得其他住宿类型的设置号)。这些是已经占用的座位号,因此请将它们存储在一组中。然后执行循环并检查该迭代的座位号是否已经在集合中 - 如果是,则跳过它,否则添加选项。

标签: java jdbc


【解决方案1】:

这是我试图解决的代码

int capacity = rs.getInt("Capacity");
List<String> list = new ArrayList<>();
for(int x = 1;x<=capacity;x++)
{
    list.add(String.format("%03d", x));
} 
pst = conn.prepareStatement("Select SeatNumber from tblcustomer WHERE TrxnDate=? AND Seat_Type=? AND ID=?");
pst.setString(1, date);
pst.setString(2, seat);
pst.setInt(3, id);
rs = pst.executeQuery();
while(rs.next())
{
    String seats = rs.getString("SeatNumber");
    list.removeIf(seats::equals);
}
Object[] objects = list.toArray();
for (Object obj : objects)
write.print("<option>"+obj+"</option>");

它可以很容易地识别出不可用和可用的座位。谢谢@Thomas

【讨论】:

    猜你喜欢
    • 2022-06-10
    • 2015-08-05
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2022-12-13
    • 2021-01-30
    • 1970-01-01
    • 2021-02-20
    相关资源
    最近更新 更多