重构非常相似 JDBC 准备好的语句

Refactoring very similar JDBC prepared statements

我正在尝试使用 JDBC 编写一些基本的 CRUD 操作。我想知道是否有一种方法可以对多个 table 使用相同的准备好的语句。现在,我为每个 table 都有一个函数,这似乎是多余的,但我不确定如何才能让它变得更好。

一些代码示例:

public static int insertIntoPeopleFilms(People people) {
    int newTableRow = -1;
    int peopleid = people.getPeopleid();
    for (URL filmUrl : people.getFilms()) {
        int filmsid = extractIdFromUrl(filmUrl);
        try (Connection conn = createDbConnection()) {
            newTableRow = getInsertIntoPeopleFilmsPreparedStatement(peopleid, filmsid, conn).executeUpdate();
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println(e);
        }
    }
    return newTableRow;
}

public static int insertIntoPeopleSpecies(People people) {
    int newTableRow = -1;
    int peopleid = people.getPeopleid();
    for (URL speciesUrl : people.getSpecies()) {
        int speciesid = extractIdFromUrl(speciesUrl);
        try (Connection conn = createDbConnection()) {
            newTableRow = getInsertIntoPeopleSpeciesPreparedStatement(peopleid, speciesid, conn).executeUpdate();
        } catch (SQLException | ClassNotFoundException e) {
            System.out.println(e);
        }
    }
    return newTableRow;
}

private static PreparedStatement getInsertIntoPeopleFilmsPreparedStatement(int peopleid, int filmsid, Connection conn) throws SQLException {
    PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO people_films(peopleid, filmsid) VALUES (?,?)");
    preparedStatement.setInt(1, peopleid);
    preparedStatement.setInt(2, filmsid);
    return preparedStatement;
}

private static PreparedStatement getInsertIntoPeopleSpeciesPreparedStatement(int peopleid, int speciesid, Connection conn) throws SQLException {
    PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO people_species(peopleid, speciesid) VALUES (?,?)");
    preparedStatement.setInt(1, peopleid);
    preparedStatement.setInt(2, speciesid);
    return preparedStatement;
}

我基本上对每个 table 都重复了相同的代码,唯一真正的区别是 table 的名称。关于减少所需代码量的任何建议?我可以使用 table 名称变量或类似的东西吗?

您不能根据某些参数创建一个插入不同 table 的准备好的语句。

标识符(例如,table 名称)必须在您准备语句时固定。在准备期间,SQL 引擎会检查您的语法并检查 table 是否存在。验证完成后,您可以自由使用准备好的语句,并且不需要在执行时进行这些检查。如果您可以在每次执行时更改 table 名称,那么 SQL 引擎每次都需要重新检查,这将部分破坏准备语句的目的。

语句准备好后,您只能更改值。换句话说,可以在您本应使用带引号的字符串文字或数字文字但不能在查询的其他部分使用的地方使用参数。