Java中MySQL数据库中订单表里查询今日已发货和未发货的数量
时间: 2023-11-27 10:54:52 浏览: 102
假设订单表名为`orders`,包含以下字段:`id` (订单ID)、`status` (订单状态)、`delivery_time` (发货时间)。其中,订单状态为1表示已发货,为0表示未发货。
以下是Java代码实现:
```java
import java.sql.*;
import java.time.LocalDate;
public class OrderStatistics {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "123456";
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 连接数据库
conn = DriverManager.getConnection(url, user, password);
// 查询今日已发货数量
String deliveredSql = "SELECT COUNT(*) FROM orders WHERE status = 1 AND delivery_time = ?";
ps = conn.prepareStatement(deliveredSql);
ps.setDate(1, Date.valueOf(LocalDate.now()));
rs = ps.executeQuery();
if (rs.next()) {
int deliveredCount = rs.getInt(1);
System.out.println("今日已发货数量:" + deliveredCount);
}
// 查询今日未发货数量
String undeliveredSql = "SELECT COUNT(*) FROM orders WHERE status = 0 AND delivery_time = ?";
ps = conn.prepareStatement(undeliveredSql);
ps.setDate(1, Date.valueOf(LocalDate.now()));
rs = ps.executeQuery();
if (rs.next()) {
int undeliveredCount = rs.getInt(1);
System.out.println("今日未发货数量:" + undeliveredCount);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (ps != null) ps.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在代码中,使用`java.sql`包中的`Connection`、`PreparedStatement`和`ResultSet`等类来进行数据库操作。首先建立数据库连接,然后分别执行查询已发货和未发货数量的SQL语句,将当前日期作为参数传递给`PreparedStatement`对象。最后关闭连接和相关对象。
阅读全文