简体   繁体   中英

Java/Groovy and MySQL: Checking if row exists in table

I am trying to check if a specific row exists in a table that includes two given parameters: record_id and modifiedDate. So far my code does not work.

public void doSomething(int RECORD_ID) {
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = new Date();
    String modifiedDate = dateFormat.format(date);

    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "user", "pass");
    Statement stmt = connection.createStatement();
    String checkIfInDB = "select exists(select * from table where reference = ${RECORD_ID} and creation_date = '${modifiedDate}');"
    ResultSet rs = stmt.executeQuery(checkIfInDB);

    if(rs.next()) {
        println "Query in db"
        stmt.close();
        connection.close();
        return;
    }

    else {
        String command = "INSERT INTO table(reference, creation_date) VALUES (${RECORD_ID}, '${modifiedDate}');"
        stmt.executeUpdate(command)
        println "Success"
        stmt.close();
        connection.close();
        return;
    }
}

If the user inserts a RECORD_ID and date that already exists, the program adds it to the table anyway, when it should print 'Query in db'. I would appreciate any help to solve this issue.

Rather than listing what was wrong with the provided code I offer an example of a working example that could be used to help you along your journey...

public static void main(String[] args) {
    int recordId = 1;

    String jdbcSource = "jdbc:mysql://localhost:####/";
    String user = "****";
    String password = "****";

    String checkIfInDB = "select count(*) as cnt from example_schema.example_table where example_table.reference = ? and example_table.creation_date = ?";

    try (Connection connection = DriverManager.getConnection(jdbcSource, user, password)) {

        PreparedStatement stmt = connection.prepareStatement(checkIfInDB);
        stmt.setInt(1, recordId);
        stmt.setDate(2, java.sql.Date.valueOf(LocalDate.now()));

        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            System.out.println("at least one row matched");
            return;
        } else {
            // to-do implement insert statement
            return;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM