JAVA代码
public boolean userReg(User user) throws SQLException, ClassNotFoundException {
Connection conn = null;
CallableStatement cs = null;
try {
conn = OracleDAOFactory.createConnection();
cs = conn.prepareCall("{call REG_USER(?,?,to_date(?,'yyyy-MM-dd'),?,?)}");
cs.setString(1, user.getEmail());
cs.setString(2, user.getPassword());
cs.setString(3, user.getBirthday());
cs.setString(4, user.getAbout());
cs.setString(5, user.getFullName());
cs.execute();
cs.close();
} catch (SQLException e) {
e.getStackTrace();
} finally {
assert conn != null;
conn.close();
}
return true;
}
Oracle SQL
CREATE OR REPLACE PROCEDURE REG_USER
(
EMAIL IN VARCHAR2,
PASSWORD IN VARCHAR2,
BIRTHDAY IN DATE,
ABOUT IN VARCHAR2,
FULLNAME IN VARCHAR2
) AS BEGIN
INSERT INTO MAILBOX_USERS VALUES(EMAIL,FULLNAME,PASSWORD,BIRTHDAY,ABOUT,1,0);
END REG_USER;
我有以下问题:
我不能在我的数据库中添加日期,在没有添加日期的情况下执行代码时,一切正常。
如何准备添加到数据库的日期字段?
答案 0 :(得分:1)
将代码更改为使用setDate
并使用java.sql.Date.valueOf(String)
传递解析日期,这需要日期字符串格式yyyy-MM-dd
public boolean userReg(User user) throws SQLException, ClassNotFoundException {
Connection conn = null;
CallableStatement cs = null;
try {
conn = OracleDAOFactory.createConnection();
cs = conn.prepareCall("{call REG_USER(?,?,?,?,?)}");
cs.setString(1, user.getEmail());
cs.setString(2, user.getPassword());
cs.setDate(3, java.sql.Date.valueOf(user.getBirthday()));
cs.setString(4, user.getAbout());
cs.setString(5, user.getFullName());
cs.execute();
cs.close();
}catch (SQLException e){
e.getStackTrace();
}finally {
assert conn != null;
conn.close();
}
return true;
}
检查this以了解有关传递日期和时间戳参数的更多信息。