I am trying to insert a record in the database if it does not exist already. The record exists if the 'description' field matches with the same field of record to be inserted.
In the code, executing the PreparedStatement has no effect on the variable 'created'. The method 'createIdea()' should return true if new record has been inserted otherwise return false (i.e. record already exists).
public static boolean createIdea(User userIns,String description,int categoryId) throws ClassNotFoundException, SQLException { PreparedStatement ps = null; Connection con = DBConnection.getConnection(); ps = con.prepareStatement("SELECT id FROM idea WHERE description = ?"); ps.setString(1, description); boolean found = ps.execute(); // If description exists ps.close(); if(found) { return false; } else { ps = con.prepareStatement("INSERT INTO idea (description, user_id, status, posted_date) VALUES (?, ?, ?, ?)"); ps.setString(1, description); ps.setInt(2, userIns.getId()); ps.setString(3, "Pending"); ps.setDate(4, new java.sql.Date(new java.util.Date().getTime())); int n = ps.executeUpdate(); ps.close(); if(n != 0) { // Other PreparedStatements } } con.close(); return true; } Table Description:
mysql> desc idea; +-------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | description | text | NO | | NULL | | | user_id | int(11) | NO | MUL | NULL | | | status | varchar(20) | NO | | NULL | | | posted_date | date | NO | | NULL | | +-------------+-------------+------+-----+---------+----------------+ The method createIdea() always returns flase. Where did I go wrong?