String month="2023-05";保存年月到表中,并以2023-05作为查询条件查询
时间: 2024-02-18 19:04:09 浏览: 20
假设您要将年月字符串`"2023-05"`保存到名为`my_table`的表中,并以`"2023-05"`作为查询条件查询,可以使用以下的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String month = "2023-05";
// 将字符串解析为LocalDate对象
LocalDate date = LocalDate.parse(month + "-01");
// 转换为java.sql.Date对象
java.sql.Date sqlDate = java.sql.Date.valueOf(date);
// 保存到数据库中
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_database", "username", "password");
String sql = "INSERT INTO my_table (year_month) VALUES (?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setDate(1, sqlDate);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 查询数据库中的数据
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_database", "username", "password");
String sql = "SELECT * FROM my_table WHERE year_month = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setDate(1, sqlDate);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
java.sql.Date resultDate = resultSet.getDate("year_month");
LocalDate resultLocalDate = resultDate.toLocalDate();
String resultMonth = resultLocalDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
System.out.println(resultMonth);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
在上面的代码中,我们首先将年月字符串解析为`LocalDate`对象,然后将其转换为`java.sql.Date`对象,并将其存储到数据库中。然后,我们使用`PreparedStatement`对象的`setDate()`方法将日期作为查询条件查询数据库,并将结果集中的日期对象转换为年月字符串输出。注意,在查询时,我们需要将`LocalDate`对象转换为`java.sql.Date`对象,并将其作为查询条件。