对于使用数据库相对较新,由于某种原因我无法让这个“执行”工作。
statment2.execute("insert into table Value (" + int + "," + date + "," + int + ",'" + string + "')");
我得到的错误是“缺少逗号”。该日期仅指定为该特定字段中的日期。
我设置如下
Date date = new Date();
date.setMonth(month);
date.setYear(year);
date.setDate(weekStart); //weekStart is always monday
我需要使用普通的旧日期还是 date.toString 吗?我打算使用日历,但我不知道如何使用日历对象设置数据库日期。我没有看到“gety/m/d”方法。
那么,是我的查询有问题还是我不正确地使用 Date 对象在数据库中设置日期?
编辑:
尝试了响应,但格式不正确 - 预期日期为数字。 尝试过
sqlDate.valueOf(dateString I created)
sqlDate.toString()
sqlDate
使用preparedStatement并不能解决这个问题,不是吗?我意识到出于安全原因它应该更好。
最佳答案
首先,您应该使用 PreparedStatement在查询中插入值。这有很多优点,包括避免 SQL Injection问题。如果您使用PreparedStatement,您将可以避免现在看到的错误。使用PreparedStatement的代码将是这样的:
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "insert into table (column1,column2,column3,column4) values(?, ?, ?,?)";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1, 1);
pstmt.setDate(2, sqlDate);
pstmt.setInt(3, 3);
pstmt.setString(3, "test");
pstmt.executeUpdate();
} catch (Exception e) {
//log the error messages log.error(e,e);
//throw the actual exception upstream
} finally {
pstmt.close();
conn.close();
}
我不确定你所说的“DB”日期是什么意思。如果您在 sql 日期对象之后,您可以通过以下方式将 java.util.Date 对象转换为 java.sql.Date 对象:
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
关于java - 数据库查询问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9672966/