我正在尝试从数据库的特定categories
表中获取具有相似类别名称的商品行,并且,对于每一行,我都进行了第二次SQL查询以求和orders table
过去一周的时间。我希望将结果添加到表模型中,但仅添加一行。
private void analyticsTableQuery(String Category) {
this.categorySelected = Category;
categoryTitle.setText(Category);
int ordered;
int initial;
String query2 = "SELECT * FROM stock INNER JOIN category ON stock.Category_id=category.id where category.Category_Name='"+Category+"'";
try {
con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","u843360242_tukule","cocaine");
pst = con.prepareStatement(query2);
rs=pst.executeQuery();
DefaultTableModel tm=(DefaultTableModel)analyticsTable.getModel();
tm.setRowCount(0);
while(rs.next()){
int id = rs.getInt("stock.id");
int current = rs.getInt("stock.Quantity");
String name = rs.getString("stock.Name");
String price = rs.getString("stock.Price");
String query = "SELECT sum(Quantity) as 'sum' FROM `orders` WHERE Created_at >= DATE(CURRENT_DATE() -7)
and Stock_id ="+id;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/u843360242_tukule
useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
pst = con.prepareStatement(query);
rs=pst.executeQuery();
rs.next();
if(rs.getInt("sum") > 0)
{
ordered = rs.getInt("sum");
initial = current + ordered;
}
else{
ordered = 0;
initial = current + ordered;
}
Object o[]={
name,
price,
initial};
tm.addRow(o);
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
您正在将结果集rs
用于外部和内部结果。用内部结果集重新初始化rs
会影响您的外部循环条件。而且即使rs
中仍然存在行,由于正在进行循环,读取id, quantity, name
等列也会导致异常,因为新结果集rs
中可能不存在这些列。