将字符串的 ArrayList 插入 MySQL JDBC 中的 table

Inserting ArrayList of String into a table in MySQL JDBC

我正在尝试使用 PreparedStatement 在循环到 MySQL 中的 table 时插入一个字符串集合。

类别 table 包含 ID (AUTOINCREMENT) 和名称。

我的方法

private ConnectionPool pool = ConnectionPool.getInstance();

@Override
public void addCategories(List<Category> category) throws SQLException {
    Connection connection = pool.getConnection();

    category = new ArrayList<>();

    try {
    PreparedStatement statement = connection
            .prepareStatement("insert into `couponsystem`.`categories` (NAME) VALUES (?)");
    for (Category categories : category) {

        statement.setString(1, category.toString());
        category.add(categories);

        statement.executeUpdate();
    }
    
    } finally {
        pool.restoreConnection(connection);
    }

}

类别class

public enum Category {

FOOD(1), ELECTRICITY(2), RESTAURANT(3), VACATION(4), HOTEL(5);

private Category(final int cat) {
    this.cat = cat;
}

private int cat;

public int getIDX() {
    return cat;
}

private Category(String cat1) {
    this.cat1 = cat1;
}

private String cat1;

public String getName() {
    return cat1;
}

}

用 MAIN 编程

List<Category> cats = new ArrayList<Category>(EnumSet.allOf(Category.class));
cat.addCategories(cats);

我没有收到任何异常,但列表保持为空。 我是 JDBC 的新手,似乎找不到解决问题的方法。

谢谢。

要批量插入您的类别,您需要使用批处理:

如上面的回答所述:

public void save(List<Entity> entities) throws SQLException {
    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setString(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

您的案例可能只适用于单个 insert 语句。

注意这一行

category = new ArrayList<>();

您在数据处理之前清除列表。 请提高代码的可读性。阅读有关名称约定的信息。例如 List 对象应该被称为 'categories',而 item - category.