簡體   English   中英

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

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

我正在嘗試檢查包含兩個給定參數的表中是否存在特定行:record_id和ModifyDate。 到目前為止,我的代碼無法正常工作。

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;
    }
}

如果用戶插入的RECORD_ID和日期已經存在,則程序應在打印“查詢數據庫”時將其添加到表中。 對於解決此問題的幫助,我將不勝感激。

我沒有列出所提供的代碼出了什么問題,而是提供了一個工作示例的示例,該示例可以用來幫助您進行工作...

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