有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当我尝试插入数据dataexecuteQuery()时,java不工作?

似乎无法解决这个问题。在过去的一个小时里,我一直在努力让它发挥作用。任何帮助都将不胜感激

INFO: Server startup in 868 ms
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().Event{id=0, name='dads', venue='dasd', startDate='11/11/11', endDate='12/11/11'}

当我尝试插入时似乎出现了错误

public void addEvent(Event event) throws DaoException{
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = this.getConnection();

            String query = "INSERT INTO TABLE EVENT VALUES(null, ?, ?, ?, ?)";         
            ps = con.prepareStatement(query);
            ps.setString(1, event.getName());
            ps.setString(2, event.getVenue());
            ps.setString(3, event.getStartDate());
            ps.setString(4, event.getEndDate());

            rs = ps.executeQuery();
        }catch(SQLException e) {
            System.out.println(event.toString());
            e.printStackTrace();
        }finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (con != null) {
                    freeConnection(con);
                }
            } catch (SQLException e) {
                throw new DaoException("Couldn't " + e.getMessage());
            }
        }
    }

共 (2) 个答案

  1. # 1 楼答案

    要插入、更新或删除,应使用executeUpdate()

    executeUpdate()返回int

    因此,将这一行rs = ps.executeQuery();替换为

    int result = ps.executeUpdate();
    

    注意按照上面的方法修改后,您会得到另一个错误,因为您的sql查询也是错误的

    使用以下查询

    INSERT INTO EVENT VALUES(null, ?, ?, ?, ?)
    
  2. # 2 楼答案

    插入查询的语法似乎不正确,请同样更新它

    INSERT INTO EVENT VALUES(null, ?, ?, ?, ?) // remove TABLE word
    //INSERT INTO TABLE_NAME VALUES(...) , this is correct syntax.
    

    这里也要正确

        executeUpdate() instead of executeQuery()
    // for insert/update/delete query always use executeUpdate(),
    // for select query use executeQuery()