使用Java for循环将多个数据插入数据库

时间:2018-10-14 06:44:01

标签: java mysql

您好,我正在从事图书馆管理项目。对于每本有多个副本的书,我需要在数据库中输入相同的详细信息,但书号不同。

public class bookentry {
      public boolean addbook(int bid,String bname, String authname, Double bprice, int edition, String pub, String catname, int bcpy) {
        boolean st = false;
        try {
            DBconnection dbconnection = new DBconnection();
            java.sql.Connection com = dbconnection.getconnection();
            for(int i=0;bid>=1;i++){
            PreparedStatement stmt = (PreparedStatement) com.prepareStatement("insert into book_master(bname, authname, bprice, edition, pub, catname, bcpy)values(?,?,?,?,?,?,?)");
            stmt.setString(1, bname);
            stmt.setString(2, authname);
            stmt.setDouble(3, bprice);
            stmt.setInt(4, edition);
            stmt.setString(5, pub);
            stmt.setString(6, catname);
            stmt.setInt(7, bcpy);
            int count = stmt.executeUpdate();
            }

1 个答案:

答案 0 :(得分:0)

您的for循环似乎不正确,因此您可以使用此for循环代码替换整个for循环,

for (int i = 0; i < bid; i++) {
    try (PreparedStatement stmt = (PreparedStatement) com
            .prepareStatement("insert into book_master(bname, authname, bprice, edition, pub, catname, bcpy)values(?,?,?,?,?,?,?)");) {
        stmt.setString(1, bname + i);
        stmt.setString(2, authname);
        stmt.setDouble(3, bprice);
        stmt.setInt(4, edition);
        stmt.setString(5, pub);
        stmt.setString(6, catname);
        stmt.setInt(7, bcpy);
        int count = stmt.executeUpdate();
    }
}

尝试让我知道您面临的进一步问题。