检索&从MySql填充.jsp页面

时间:2012-01-07 03:28:07

标签: java mysql

我如何检索&使用MySQL在.jsp页面填充输出组件?另外,我如何检索有关特定item_id的记录?我正在使用IBM Rational Application Developer。

以下是我到目前为止所遇到的错误或缺失的陈述,我敢肯定。

@ DB.class

public Items getItemDetails() {
                     Connection con = connect(true);
            PreparedStatement stmt = null;
            ResultSet rs = null;
            String select = "SELECT * FROM TEST.ITEMBOUGHT WHERE ITEM_ID = ?";
            Items item = null;

            try {
                stmt = con.prepareStatement(select);
                //stmt.setString(1,item_id);
                rs = stmt.executeQuery();
                while (rs.next()) {
                    //System.out.println("Record Found!");
                    item = new Items();
                    //item.setItem_id(item_id);
                    item.setItem_name(rs.getString("item_name"));
                    item.setItem_bidding_start_price(rs.getDouble("item_bidding_starting_price"));
                    item.setItem_bidding_highest_price(rs.getDouble("item_bidding_highest_price"));
                    item.setItem_description(rs.getString("item_description"));
                    item.setItem_quantity(rs.getInt("item_quantity"));
                    item.setItem_closing_date(rs.getDate("item_closing_date"));
                    item.setItem_image(rs.getString("item_image"));
                    item.setItem_status(rs.getString("item_closing_date"));
                }
            } catch (Exception e) {
                e.printStackTrace();
                item = null;
            } finally {
                try {
                    if (rs   != null) rs.close();
                    if (stmt != null) stmt.close();
                    if (con  != null) con.close();
                } catch (SQLException e) {}
            }
            return item;
        }

1 个答案:

答案 0 :(得分:0)

您正在为SQL使用PreparedStatement:SELECT * FROM TEST.ITEMBOUGHT WHERE ITEM_ID = ?。这意味着您必须告诉JDBC在查询字符串中替换问号(?)的值是什么,但是您在//stmt.setString(1,item_id);

中对其进行了注释

如果要选择ITEM_ID 1且ITEM_ID为INTEGER(数字字段),则可以使用以下代码:

public Items getItemDetails() {
   Connection con = connect(true);
   PreparedStatement stmt = null;
   ResultSet rs = null;
   String select = "SELECT * FROM TEST.ITEMBOUGHT WHERE ITEM_ID = ?";
   Items item = null;

   try {
       stmt = con.prepareStatement(select);
       stmt.setInt(1,1);
       rs = stmt.executeQuery();
       while (rs.next()) {
          ... // and so on
       }
   }
   ...
}

如果要选择所有记录,请删除WHERE子句:SELECT * FROM TEST.ITEMBOUGHT。如果您不需要PreparedStatement,可以将代码重写为:

Statement stmt = null;
...
try {
...
   stmt = con.createStatement() ;
   rs = stmt.executeQuery(select) ;
...
}