从java更新不在mariadb中的列

时间:2017-02-27 14:00:34

标签: java mariadb mariadb-connect-engine

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

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

以下是代码段: Java Code Snippet

抛出异常: Exception Trace

1 个答案:

答案 0 :(得分:1)

您可以使用Statement.executeUpdate()代替。 因此,您还需要将SELECT语句更改为UPDATE语句。

缺点是您无法访问单行数据,因为您根本不会选择它。如果你需要这个,例如要计算更新后的值(在您的情况下为test@<localipaddress>),您可能必须先按照您的选择启动选择,在内存中计算更新,然后使用PreparedStatementBatch 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;
    }