纯jsp将入库信息(id,供应商名称,商品名称,类型,入库数量,入库时间)增加到入库表,同时将(id,商品名称,类型,入库数量)增加到库存表
时间: 2023-06-27 20:05:59 浏览: 93
jsp商品库存进销存管理系统 |
假设你已经连接好了数据库,以下是一个简单的纯JSP示例代码:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
// 获取表单提交的数据
String supplierName = request.getParameter("supplierName");
String productName = request.getParameter("productName");
String type = request.getParameter("type");
int quantity = Integer.parseInt(request.getParameter("quantity"));
// 建立数据库连接
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
// 向入库表插入数据
String sql1 = "INSERT INTO instock (supplier_name, product_name, type, quantity, instock_time) VALUES (?, ?, ?, ?, NOW())";
pstmt1 = conn.prepareStatement(sql1);
pstmt1.setString(1, supplierName);
pstmt1.setString(2, productName);
pstmt1.setString(3, type);
pstmt1.setInt(4, quantity);
pstmt1.executeUpdate();
// 向库存表插入数据
String sql2 = "INSERT INTO inventory (product_id, product_name, type, quantity) VALUES (LAST_INSERT_ID(), ?, ?, ?)";
pstmt2 = conn.prepareStatement(sql2);
pstmt2.setString(1, productName);
pstmt2.setString(2, type);
pstmt2.setInt(3, quantity);
pstmt2.executeUpdate();
// 提交事务
conn.commit();
} catch (Exception e) {
// 出错回滚事务
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
} finally {
// 关闭连接和语句对象
if (pstmt1 != null) {
try {
pstmt1.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt2 != null) {
try {
pstmt2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
```
上面的代码中,我们首先获取了表单提交的数据,然后建立了数据库连接。接着,我们分别向入库表和库存表插入数据,其中第二个插入语句使用了MySQL的`LAST_INSERT_ID()`函数获取上一次插入操作生成的自增ID,以作为当前插入操作的外键。最后,我们提交或回滚事务,并且关闭连接和语句对象。注意,以上示例代码仅供参考,实际开发中需要根据具体情况进行修改和完善。
阅读全文