在自学java的过程中遇到 将date类型的数据存入数据库
package com.atguigu2.preparedstatement.crud;
import com.atguigu.connection.ConnectionTest;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
public class PreparedStatementUpdateTest {
//向customers 添加一条数据
@Test
public void testInsert() {
Connection conn = null;
PreparedStatement ps = null;
try {
// 1.读取文件中的基本信息
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
// 2.加载驱动
Class.forName(driverClass);
conn = DriverManager.getConnection(url, user, password);
// System.out.println(conn);
// 4.预编译sql语句
String sql = "INSERT INTO customers(name,email,birth)VALUES(?,?,?)";
ps = conn.prepareStatement(sql);
//5.填充暂位符
ps.setString(1,"张三");
ps.setString(2,"zhangsan@gmail.com");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse("1000-01-01");
// ps.setDate(3, (java.sql.Date) new Date(date.getTime()));
ps.setDate(3, new java.sql.Date(date.getTime()));
//6.用户执行sql
ps.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
//7.资源关闭
try {
if(ps != null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
这么修改完就ok啦