java - 将字符串的 ArrayList 插入 MySQL JDBC 中的表中
问题描述
我正在尝试在使用 PreparedStatement 循环到 MySQL 中的表时插入字符串集合。
类别表包含 ID (AUTOINCREMENT) 和 NAME。
我的方法
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);
}
}
类别类
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;
}
}
主程序
List<Category> cats = new ArrayList<Category>(EnumSet.allOf(Category.class));
cat.addCategories(cats);
我没有得到任何异常,但是列表保持为空。我对 JDBC 有点陌生,似乎找不到解决它的问题。
谢谢。
解决方案
对于您的类别的批量插入,您需要使用批次: https ://stackoverflow.com/a/4355097/6916890
如上面的答案所述:
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
陈述。
推荐阅读
- python - 包括记录器类的对象清单类覆盖字典条目
- sql - 使用内部连接更新表
- redirect - 在 Razor 页面中重定向到带有 ID 的页面
- google-sheets - 更新文件夹和子文件夹中所有文件中的单个工作表
- android - Android 移动应用程序可绘制图标下载
- bootstrap-4 - Bootstrap 4手风琴不会自动关闭以前打开的部分
- javascript - 混合内容:HTTP 问题
- c# - 根据 Entity Framework Core 中的不同列选择所有行
- json - 如何将 JSON 提交到 PowerShell RestMethod 或 WebRequest
- ruby - 是否可以覆盖接收器行为?