package?com.DAO;
import?java.sql.Connection;
import?java.sql.SQLException;
import?java.util.ArrayList;
import?java.sql.PreparedStatement;
import?java.sql.ResultSet;
import?java.sql.Statement;
import?com.utilty.DBHelper;
import?entity.Items;
public?class?ItemsDao?{
public?ArrayList<Items>?getAllItems()?{
PreparedStatement?ptmt?=?null;
ResultSet?rs?=?null;
Connection?conn?=?null;
ArrayList<Items>?itemList?=?new?ArrayList<Items>();//?商品集合
try?{
conn?=?DBHelper.getConnection();
String?sql?=?"select?*?from?items;";//?sql語句
ptmt?=?conn.prepareStatement(sql);
rs?=?ptmt.executeQuery();
while?(rs.next())?{
Items?item?=?new?Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setPrice(rs.getInt("price"));
item.setNumber(rs.getInt("number"));
item.setPicture(rs.getString("picture"));
itemList.add(item);//?把一個商品加入到集合中
}
return?itemList;
}
catch?(Exception?ex)?{
ex.printStackTrace();
}?finally?{
if?(rs?!=?null)?{
try?{
rs.close();
rs?=?null;
}?catch?(SQLException?e)?{
e.printStackTrace();
}
}
if?(ptmt?!=?null)?{
try?{
ptmt.close();
ptmt?=?null;
}?catch?(SQLException?e)?{
e.printStackTrace();
}
}
}
//?返回商品集合
}
}


2015-12-24
因為可能在執(zhí)行try里面的語句時可能出錯,如果出錯了就沒有返回值了,就會出現(xiàn)錯誤。
而放在finally后面不過try里面是否出錯,這里面的語句都會執(zhí)行。
2022-03-26
不可以。有漏洞不嚴(yán)謹(jǐn)。nbsp;先判斷if條件,然后直接走else的結(jié)果了,也就是說無論你的else寫的什么返回結(jié)果都會執(zhí)行。符合條件就做什么沒有就做什么,else沒有條件