如何使用servlet从mysql数据库中检索数据?

时间:2019-07-11 13:04:25

标签: mysql eclipse jsp servlets

我正在建立一个购物网站,使用html和CSS作为前端,使用mysql数据库和servlet作为后端。我希望使用已存储的servlet从数据库中动态检索用户可以购买的项目,然后在用户单击“添加到购物车”时将其添加到购物车。我被困在必须动态检索产品的地步。

我有一个带有列的产品库存表:

pid       varchar(30)
pname     varchar(30)
price     int(4)
quantity  int(4)
image     blob
file_name varchar(255)

代码”

try {
    Class.forName("com.mysql.cj.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/amacon2","root","root");
    Statement st = con.createStatement();

    String query = "SELECT * from product";
    ResultSet rs = st.executeQuery(query);
    while (rs.next()) {
        String pid = rs.getString("pid");
        String pname = rs.getString("pname");
        int price = rs.getInt("price");
        int quantity = rs.getInt("quantity");
        Blob blob = rs.getBlob("image");
        byte byteArray[] = blob.getBytes((int)blob.length());
        response.setContentType("image/jpeg");
        OutputStream os = response.getOutputStream();
        os.write(byteArray);
        os.flush();
        os.close(); 

        // byte image = rs.getByte("image");
        String file_name = rs.getString("file_name");
        out.print(pid + "::");
        out.print(pname+ "::");
        out.print(price + "::");
        out.print(quantity + "::");
        // out.print(image + "::");
        out.print(file_name+ "::");
    }

0 个答案:

没有答案