当我尝试o插入数据dataexecuteQuery()不起作用?

时间:2015-12-04 11:15:26

标签: java mysql

无法解决这个问题。过去一小时一直试图让它工作。任何帮助将不胜感激。

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 个答案:

答案 0 :(得分:1)

用于插入或更新或删除您应使用executeUpdate()

executeUpdate()返回int

所以用

替换此行rs = ps.executeQuery();
int result = ps.executeUpdate();

注意按照上面的说法修改后会出现另一个错误因为你的SQL查询也错了

使用以下查询

INSERT INTO EVENT VALUES(null, ?, ?, ?, ?)

答案 1 :(得分:0)

它看起来像INSERT查询的错误语法,同样更新

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()