从 java 更新列在 mariadb 中不起作用

Updating column not working in mariadb from java

我在通过 java 代码的 mariadb 中的结果集更新列值时遇到问题。看起来 mariadb JDBC 连接器不支持 resultset.updateString() 方法,任何人都可以给我发送执行此过程的替代方法。

MariaDB 连接器版本:mariadb-java-client-1.5.8.jar, MariaDB 版本:mariadb-10.1.20-winx64

以下是代码片段: Java Code Snippet

抛出以下异常: Exception Trace

您可以改用 Statement.executeUpdate()。 当然,您也需要将 SELECT 语句更改为 UPDATE 语句。

缺点是您无法访问单行数据,因为您根本 select 它。如果你需要这个,例如要计算更新值(在您的情况下 test@<localipaddress>),您可能必须像您一样首先触发 select,计算内存中的更新,然后使用 PreparedStatement or Batch Update 执行相应的 UPDATE 语句。

准备好的语句示例:

public static int preparedUpdate(Connection conn, String localIPAddress) throws SQLException {
        int numChangedRows = 0;

            try (Statement stmt = conn.createStatement()) {
                ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
                while (rs.next()) {
                    // id => something unique for this row within the table,
                    // typically the primary key
                    String id = rs.getString("id");
                    String jid = rs.getString("column1");
                    if("abc".equals(jid)) { // just some nonsense condition
                        try (PreparedStatement batchUpdate = conn.prepareStatement("UPDATE table1 SET column1 = ? where id = ?")) {
                            batchUpdate.setString(1, localIPAddress);
                            batchUpdate.setString(2, id);
                            numChangedRows = batchUpdate.executeUpdate();
                        }
                    }
                }
        }
        return numChangedRows;
    }

批量更新示例:

public static int[] batchUpdate(Connection conn, String localIPAddress) throws SQLException {
        int[] changedRows = null;
        try (PreparedStatement batchUpdate = conn.prepareStatement("UPDATE table1 SET column1 = ? where id = ?")) {
            try (Statement stmt = conn.createStatement()) {
                ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
                while (rs.next()) {
                    // id => something unique for this row within the table,
                    // typically the primary key
                    String id = rs.getString("id");

                    String jid = rs.getString("column1");
                    if("abc".equals(jid)) { // just some nonsense condition
                        batchUpdate.setString(1, localIPAddress);
                        batchUpdate.setString(2, id);
                        batchUpdate.addBatch();
                    }
                }
            }
            changedRows = batchUpdate.executeBatch();
        }
        return changedRows;
    }