【问题标题】:How to insert multiple rows in a SQL Database如何在 SQL 数据库中插入多行
【发布时间】:2019-08-17 22:01:09
【问题描述】:

我正在开发一本食谱书,但在数据库中保存同一食谱的多个成分时遇到了问题。我可以添加,按一个按钮,在一个成分 EditText 和一个数量 EditText 内添加多个线性布局。 因此 for 循环评估每个布局,它采用当前的成分和数量值将它们保存在 newIngredient 实例(Ingredient.class)中。然后它将实例插入数据库,最后,将实例添加到我的“成分”ArrayList 并关闭数据库。通过调试,我发现所有这些都只适用于 for 循环的第一次迭代。

for (int d=0; d<countIngredients; d++) {
        View childViewIng = parentIngredientLayout.getChildAt(d);
        EditText childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
        EditText childTextViewQ = childViewIng.findViewById(R.id.quantityField);
        childIngredient = childTextViewI.getText().toString();
        childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
        newIngredient = new Ingredient(childIngredient, childQuantity);
        dbHelper.insertIngredient(newIngredient);
        ingredients.add(newIngredient);
        dbHelper.close();
    }

【问题讨论】:

  • 尝试将dbHelper.close();移到for循环之外
  • 你是否得到任何数据库已经关闭的异常?

标签: android sql database class arraylist


【解决方案1】:

在您的代码中,您将关闭 for 循环内的数据库。

因此,您的代码将执行第一次迭代,然后关闭数据库,因此下一次迭代将由于关闭的数据库连接而失败。

您应该将您的 dbHeloper.close(); 呼叫移到循环之外。

为了更好地使用内存,您可以将变量移到 for 循环之外。简而言之:

第一步:循环结束后关闭数据库

for (int d=0; d < countIngredients; d++) {
    View childViewIng = parentIngredientLayout.getChildAt(d);
    EditText childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
    EditText childTextViewQ = childViewIng.findViewById(R.id.quantityField);
    childIngredient = childTextViewI.getText().toString();
    childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
    newIngredient = new Ingredient(childIngredient, childQuantity);
    dbHelper.insertIngredient(newIngredient);
    ingredients.add(newIngredient);
}
//move close method here, outside loop
dbHelper.close();

第 2 步:优化变量

//move variables here, or wherever you want
View childViewIng = null;
EditText childTextViewI = null;
EditText childTextViewQ = null;

for (int d=0; d < countIngredients; d++) {
    //in this way you will create only 1 object, and reuse it every time
    childViewIng = parentIngredientLayout.getChildAt(d);
    childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
    childTextViewQ = childViewIng.findViewById(R.id.quantityField);
    childIngredient = childTextViewI.getText().toString();
    childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
    newIngredient = new Ingredient(childIngredient, childQuantity);
    dbHelper.insertIngredient(newIngredient);
    ingredients.add(newIngredient);
}
dbHelper.close();

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    相关资源
    最近更新 更多