<pre name="code" class="java">package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.bean.Item;
import com.util.DBConnection;
//商品业务逻辑
public class ItemDAO {
public ItemDAO() {
// TODO Auto-generated constructor stub
}
public ArrayList<Item> getAllitems() {
Connection con = null;
PreparedStatement stmt = null;
String sql = "select * from items";//sql语句
ResultSet rs = null;
ArrayList<Item> items = new ArrayList<Item>();//商品集合
try {
con = DBConnection.getConnection();
stmt = con.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Item item = new Item();
item.setId(rs.getInt(1));
item.setName(rs.getString(2));
item.setCity(rs.getString(3));
item.setPrice(rs.getInt(4));
item.setImage(rs.getString(5));
items.add(item);
}
return items;//返回商品集合
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} finally {
//释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public Item getItemsByID(int id)
{
String sql = "select * from items where id=?";
ResultSet rs = null;
Connection con = null;
PreparedStatement stmt=null;
try {
con = DBConnection.getConnection();
stmt = con.prepareStatement(sql);
stmt.setInt(1,id);
rs = stmt.executeQuery();
if(rs.next())
{
Item item = new Item();
item.setId(rs.getInt(1));
item.setName(rs.getString(2));
item.setCity(rs.getString(3));
item.setPrice(rs.getInt(4));
item.setImage(rs.getString(5));
return item;
}
else
{
return null;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} finally
{
if(rs!=null)
{
try {
rs.close();
rs=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt!=null)
{
try {
stmt.close();
stmt=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public ArrayList<Item> getViewedItemsList(String list)
{
String[] arr = list.split(",");//获取浏览过的商品编号数组
ArrayList<Item> items = new ArrayList<Item>();
int count = 0;//计数,返回前五条浏览记录
int num=arr.length-1;//浏览记录条数
System.out.println("arr长度:"+num);
if(list!=null&&list.length()>0)//判空,防止空指针错误
{
if(num>5)//如果记录大于五条
{
while(count++<5)
{
//System.out.println(arr[num]);
items.add(getItemsByID(Integer.parseInt(arr[num--])));
}
}
else
{
while(num>=0)
{
items.add(getItemsByID(Integer.parseInt(arr[num--])));
}
}
}
return items;
}
}
Jsp动态网站初步项目 --简单的商品浏览页面(ItemDAO业务逻辑类)
最新推荐文章于 2022-04-06 22:51:21 发布