纯用jsp增加商品入库信息(id,供应商名称,商品名,类型,入库数量),同时将(id,商品名,类型,入库数量)增加到库存表中
时间: 2023-06-27 09:06:44 浏览: 145
首先,需要在后台编写一个jsp页面,通过表单的方式获取商品的入库信息,然后将该信息存储到数据库中,并且更新库存表。
以下是一个简单的示例代码:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>商品入库</title>
</head>
<body>
<h1>商品入库</h1>
<form action="add_goods.jsp" method="post">
<label for="supplier">供应商名称:</label>
<input type="text" name="supplier" id="supplier" required><br><br>
<label for="name">商品名称:</label>
<input type="text" name="name" id="name" required><br><br>
<label for="type">商品类型:</label>
<input type="text" name="type" id="type" required><br><br>
<label for="quantity">入库数量:</label>
<input type="number" name="quantity" id="quantity" required><br><br>
<input type="submit" value="提交">
</form>
<%
// 获取表单数据
String supplier = request.getParameter("supplier");
String name = request.getParameter("name");
String type = request.getParameter("type");
int quantity = Integer.parseInt(request.getParameter("quantity"));
// 数据库连接
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
// 插入商品入库信息到商品表中
pstmt = conn.prepareStatement("INSERT INTO goods (supplier, name, type, quantity) VALUES (?, ?, ?, ?)");
pstmt.setString(1, supplier);
pstmt.setString(2, name);
pstmt.setString(3, type);
pstmt.setInt(4, quantity);
pstmt.executeUpdate();
// 更新库存表
pstmt = conn.prepareStatement("SELECT * FROM stock WHERE name = ? AND type = ?");
pstmt.setString(1, name);
pstmt.setString(2, type);
rs = pstmt.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
int oldQuantity = rs.getInt("quantity");
int newQuantity = oldQuantity + quantity;
pstmt = conn.prepareStatement("UPDATE stock SET quantity = ? WHERE id = ?");
pstmt.setInt(1, newQuantity);
pstmt.setInt(2, id);
pstmt.executeUpdate();
} else {
pstmt = conn.prepareStatement("INSERT INTO stock (name, type, quantity) VALUES (?, ?, ?)");
pstmt.setString(1, name);
pstmt.setString(2, type);
pstmt.setInt(3, quantity);
pstmt.executeUpdate();
}
out.println("<p>商品入库成功!</p>");
} catch (Exception e) {
e.printStackTrace();
out.println("<p>商品入库失败!</p>");
} finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
</body>
</html>
```
在该代码中,我们首先通过表单获取了商品的入库信息,然后将该信息插入到商品表中。接着,我们查询库存表中是否已经存在该商品的记录,如果存在,则更新该记录的数量,否则插入一条新的记录。最后,我们将操作结果输出到页面上。
需要注意的是,该示例代码仅供参考,实际代码需要根据具体业务需求进行修改。同时,该代码还存在SQL注入等安全问题,需要进行进一步的加强防护。
阅读全文