我正在开发一个需要计算日期的项目。我正在寻找一种方法将日期存储为访问数据库中的日期对象,但每个方法都会出错。我在Java 8中使用UcanAccess驱动程序。
我的剥离代码:
//========================== SetupDB =====================================//
public void setupDB() {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
c1 = DriverManager.getConnection(ABDebatePro.DBURL);
stmt = c1.createStatement();
}
catch (Exception e) {
System.out.println(e);
}
}
//========================== InsertDB ====================================//
public void insertDB(int m, String ft, String st, int s1, int s2, Date d) {
MatchNumber = m;
FirstTeam = ft;
SecondTeam = st;
FirstTeamScore = s1;
SecondTeamScore = s2;
MatchDate = d;
setupDB();
try {
String sql = "insert into Schedule (MatchNumber, FirstTeam, SecondTeam, FirstTeamScore, SecondTeamScore, MatchDate) values " + "(" + m + ",'" + ft + "','" + st + "'," + s1 + "," + s2+ ",'" + d + "')";
int z = stmt.executeUpdate(sql);
c1.close();
} catch (Exception fe) {
System.out.println(fe);
}
}
//========================== Main ========================================//
public static void main(String[] args) {
Schedule sch = new Schedule();
try {
java.sql.Date date1 = java.sql.Date.valueOf("2016-10-25");
sch.insertDB(3, "Turtles", "Aligators", 4, 3, date1);
} catch (Exception ex) {
System.out.println(ex);
}
我的日志:
insert into Schedule (MatchNumber, FirstTeam, SecondTeam, FirstTeamScore, SecondTeamScore, MatchDate) values (3,'Turtles','Aligators',4,3,'2016-10-25')
net.ucanaccess.jdbc.UcanaccessSQLException: data exception: invalid datetime format
我的数据库:
答案 0 :(得分:2)
您的问题是您正在使用动态SQL 在insertDB
中构造SQL语句,并且该语句包含无效的日期文字。您应该使用PreparedStatement
和参数化查询,如下所示:
String sql =
"INSERT INTO Schedule " +
"(MatchNumber, FirstTeam, SecondTeam, FirstTeamScore, SecondTeamScore, MatchDate) " +
"VALUES " +
"(?,?,?,?,?,?)"
PreparedStatement ps = c1.prepareStatement(sql)
ps.setInt(1, m);
ps.setString(2, ft);
ps.setString(3, st);
ps.setInt(4, s1);
ps.setInt(5, s2);
ps.setDate(6, d);
int z = ps.executeUpdate();
答案 1 :(得分:-1)
您的示例方法:
public void getSqlDate() {
Calendar cal = Calendar.getInstance();
int year = 2016;
int month = 9; //month is zero-based
int day = 25
cal.set(year, month, date);
return new Date(cal.getTime());
}
请注意,java.sql.Date的构造函数确实需要一个long值,表示自1970年1月1日00:00:00 GMT"
以来的#"毫秒请参阅JavaDocs java.sql.Date