我编写了一个方法存根,到目前为止我在PreparedStatement中有这个SQL查询:
PreparedStatement ps = connection.prepareStatement("SELECT id,itemId,userId, sum(I.price) as totalAmount FROM dbo.Orders o
join dbo.Items I on o.itemId = I.id join dbo.Users u on o.UserId = u.Id where o.id = ?");
ps.setInt(1, id);
要求: 检索给定订单ID的不同项目值,并将它们添加到arrayList。
以下是我的方法到目前为止的样子:
public ArrayList<Orders> GetOrders(Connection connection) throws Exception
{
ArrayList<Orders> feedData = new ArrayList<Orders>();
ArrayList<Integer> itemsId = new ArrayList<Integer>();
//How do I get items in this arraylist since there could be multiple items for a given order ?
try
{
PreparedStatement ps = connection.prepareStatement("SELECT id,itemId, userId, sum(I.price) as totalAmount FROM dbo.Orders o join dbo.Items I on o.itemId = I.id join dbo.Users u on o.UserId = u.Id where o.id = ? group by o.id");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
Orders o = new Orders();
o.setId(rs.getInt("id"));
//how do I add elements itemid's in itemsId array list here.?
while(){
}
o.setItem(itemsId);
o.setUserId(rs.getInt("price"));
o.setTotalAmount(rs.getInt("totalAmount"));
feedData.add(o);
}
return feedData;
}
catch(Exception e)
{
throw e;
}
}
编辑:
数据库架构:
create table Users
(
Id int not null primary Key identity(1,1) constraint fk_UserId_Id references Orders(UserId),
name nvarchar(50),
phone nvarchar(10)
);
create table Items
(
Id int not null primary Key identity(1,1) constraint fk_item_Id references Orders(ItemId),
name nvarchar(50),
Price int
);
create table Orders
(
id int not null primary Key identity(1,1),
ItemId int,
UserId int,
);
答案 0 :(得分:0)
//这就是你要找的东西吗?
pushStore.getString("url")
答案 1 :(得分:0)
基本上,您需要遍历所有返回的记录,即使您只想加载一个订单对象。
这是我所做的快速模拟,所以推迟批评,是的,它可以更好地实施。
public ArrayList<Orders> GetOrders( Connection connection ) throws Exception {
ArrayList<Orders> feedData = new ArrayList<Orders>();
int id = 0; // your Order ID
try {
PreparedStatement ps = connection.prepareStatement( "SELECT id,itemId, userId, sum(I.price) as totalAmount FROM dbo.Orders o join dbo.Items I on o.itemId = I.id join dbo.Users u on o.UserId = u.Id where o.id = ? group by o.id" );
ps.setInt( 1, id );
ResultSet rs = ps.executeQuery();
ArrayList<Integer> itemsId = new ArrayList<Integer>();
Orders o = new Orders();
boolean populateOrder = true;
while( rs.next() ) {
itemsId.add( rs.getInt( "itemId" ) );
if( populateOrder ) {
o.setId( rs.getInt( "id" ) );
o.setUserId( rs.getInt( "price" ) );
o.setTotalAmount( rs.getInt( "totalAmount" ) );
feedData.add( o );
populateOrder = false; // make sure this If executes only once
}
}
o.setItem( itemsId );
return feedData;
} catch( Exception e ) {
throw e;
}
}
以上示例有一个很大的限制,即它仅适用于单个订单(一个订单ID)。如果您希望加载多个代码需要更改的订单。