数据库查询问题

时间:2012-03-12 18:47:09

标签: java database date jdbc

使用数据库相对较新,出于某种原因,我无法让“执行”工作。

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

我是否需要使用普通的旧日期或日期.toString?我打算使用Calendar但我不知道如何使用Calendar对象设置DB日期。我没有看到“gety / m / d”方法。

那么,问题是我的查询还是我不正确地使用Date对象在数据库中设置日期?

编辑:

尝试了回复,格式不正确 - 预期日期得到了号码。 试图

sqlDate.valueOf(dateString I created)
sqlDate.toString()
sqlDate

使用preparedStatement不会解决这个问题吗?我意识到出于安全原因它应该更好。

1 个答案:

答案 0 :(得分:2)

首先,您应该使用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 date对象之后,可以用这种方式将java.util.Date对象转换为java.sql.Date对象:

java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
相关问题