通过Java生成多个插入查询

时间:2019-04-16 04:46:23

标签: java mysql jsp servlets jdbc

我有此查询”插入pro_vendor(供应商名称,super_category,sub_category,created_by,vowes,wowes,created_date,status)值('V','Sup','Sub',' user','0','0',CURRENT_TIMESTAMP'active')“

如果需要处理结果集,我通常通过预准备语句或仅通过statement.executeQuery(query)实现单行代码。

现在的事情是,我有一个数组,其中第一个参数即vendor_name有多个(也许是1,也许是2,也许是50)不同的替代方案,所以我想使用循环生成插入查询。

我无法使用准备好的语句,因为我无法动态生成准备好的语句对象,对于executeQuery来说,就像我无法动态生成的语句对象一样。

我要问的是一种根据数组大小生成插入查询的方法,谢谢。

1 个答案:

答案 0 :(得分:2)

我认为要插入多个记录,必须使用批量插入。

Connection conn;
        try {
            conn = DriverManager.getConnection("connection parameter's");

            Statement stmt = conn.createStatement();  // establish connection and make a table for the data.


            // COPY statement
            conn.setAutoCommit(false);


            // Drop table and recreate.
            stmt.execute("DROP TABLE IF EXISTS customers CASCADE");
            stmt.execute("CREATE TABLE customers (CustID int, Last_Name  char(50), First_Name char(50),Email char(50), "
                            + "Phone_Number char(12))");

            // Some dummy data to insert. 
            String[] firstNames = new String[] { "Anna", "Bill", "Cindy","Don", "Eric" };
            String[] lastNames = new String[] { "Allen", "Brown", "Chu", "Dodd", "Estavez" };
            String[] emails = new String[] { "aang@example.com", "b.brown@example.com", "cindy@example.com","d.d@example.com", "e.estavez@example.com" };
            String[] phoneNumbers = new String[] { "123-456-7890", "555-444-3333", "555-867-5309", "555-555-1212", "781-555-0000" };
            // Create the prepared statement
            PreparedStatement pstmt = conn.prepareStatement("INSERT INTO customers (CustID, Last_Name, " + 
                            "First_Name, Email, Phone_Number)  VALUES(?,?,?,?,?)");

            // Add rows to a batch in a loop. Each iteration adds a
            for (int i = 0; i < firstNames.length; i++) {

                pstmt.setInt(1, i + 1);
                pstmt.setString(2, lastNames[i]);
                pstmt.setString(3, firstNames[i]);
                pstmt.setString(4, emails[i]);
                pstmt.setString(5, phoneNumbers[i]);
                pstmt.addBatch();  // Add row to the batch.
            }

            try {
                // Batch is ready, execute it to insert the data
                pstmt.executeBatch();
            } catch (SQLException e) {
                System.out.println("Error message: " + e.getMessage());
                return; // Exit if there was an error
            }

            // Commit the transaction to close the COPY command
            conn.commit();
            conn.close();