Java代码里面字符类型日期数据怎么存进MySQL里面
时间: 2023-12-05 10:04:37 浏览: 39
要将字符类型的日期数据插入到MySQL数据库中,需要将其转换为日期类型,并使用INSERT INTO语句将其插入到表中。以下是一个示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class InsertDate {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
// 待插入数据
String dateString = "2020-01-01";
String value = "1000";
// 字符串转日期
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
// 数据库插入操作
try {
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO test_table (date_column, value_column) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDate(1, new java.sql.Date(date.getTime()));
ps.setString(2, value);
int result = ps.executeUpdate();
System.out.println(result + " rows affected");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,我们先将字符串类型的日期数据转换为日期类型,然后使用PreparedStatement对象将日期类型和其他数据一起插入到MySQL数据库中。注意,我们使用了java.sql.Date类将Java的日期类型转换为MySQL的日期类型。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)