更新列在Java中不用在Mariadb中工作



我面临问题的问题,从java代码中的mariaDB中更新列值。看起来resultset.updatestring()方法在Mariadb JDBC连接器中不支持,任何人都可以给我发送此过程的替代方法。

Mariadb连接器版本:Mariadb-Java-Client-1.5.8.Jar,Jar,Mariadb版本:Mariadb-10.1.20-winx64

以下是代码段:Java代码段

以下例外抛出:异常跟踪

您可以使用statement.executeupdate()。原因您也需要将SELECT语句也更改为更新语句。

缺点是,您完全不选择它。如果需要,例如要计算更新的值(在您的情况下,test@<localipaddress>),您可能必须像以前一样首先启动选择,请计算内存中的更新,然后使用准备的statement或批处理更新以根据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;
    }

最新更新