简体   繁体   English

Java / Groovy和MySQL:检查表中是否存在行

[英]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. 我正在尝试检查包含两个给定参数的表中是否存在特定行:record_id和ModifyDate。 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'. 如果用户插入的RECORD_ID和日期已经存在,则程序应在打印“查询数据库”时将其添加到表中。 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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