通过sql表中的java更新随机行中的值



启动此程序时我的表的图像。

我所拥有的是一个几乎为空的表,我正试图为固定数量的元素赋值。我试图编辑的列是"Geschlecht",我要编辑的行数是"copyMeen"(约50000个条目)。我只想选择之前"Geschlecht"值为NULL的行,并且我想随机选择这些行。

我通过JDBC驱动程序使用SQLite。

这是我第一次使用sql。这就是我试图做到的。

                try {
        Statement stmt = DBController.connection.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT Geschlecht FROM individuen WHERE Geschlecht IS NULL;");
        PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen");
        while (copyMaen != 0) {
            if (rs.getRowId((int) (Math.random() * ReadCSV.sumBev)) == null) {
                ps.setInt(2, 0);
                ps.executeUpdate();
                copyMaen--;
            }
        }
        rs.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }

很明显,这让我犯了错误,我真的不知道该怎么做。有人能给我指正确的方向吗?

对于任何感兴趣的人来说,这就是解决方案:

try {
        Statement stmt = DBController.connection.createStatement();
        String select = "SELECT ID FROM individuen WHERE Geschlecht is NULL ORDER BY RANDOM()" +
        " LIMIT " + Integer.toString(copyMaen);
        ResultSet rs = stmt.executeQuery(select);
        PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen set Geschlecht  = ? WHERE ID = ?;");
        // rs.beforeFirst();
        int count = 0;
        while (rs.next()) {
            ps.setInt(1, 0);
            ps.setInt(2, rs.getInt(1));
            ps.addBatch();
            if (count%100==0) {
                System.out.println(count);
            }
            count++;
        }
        DBController.connection.setAutoCommit(false);
        ps.executeBatch();
        DBController.connection.setAutoCommit(true);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

试试这个,

下面的更新查询足以更新Geschlecht所在的所有行无效的

try {
        Statement stmt = DBController.connection.createStatement();
        String updateTableSQL = "UPDATE individuen set Geschlecht  = ? where Geschlecht IS NULL";
        PreparedStatement preparedStatement = dbConnection.prepareStatement(updateTableSQL);
        preparedStatement.setString(1, "0"); // set zero where Geschlecht null found
        // execute update SQL stetement
        preparedStatement.executeUpdate();
} catch (SQLException e) {
        e.printStackTrace();
}

最新更新