3

Java:使用 PreparedStatement 将多行插入 MySQL包括将多个 INSERT 批处理到一个操作中。我想知道是否可以对存储过程的调用做同样的事情,更具体地说是对 MySQL 的调用?如果是这样,将使用什么语句类?

4

2 回答 2

3

如果您有这样的存储过程:

JDBC CallableStatement Stored procedure IN parameter example.
CREATE OR REPLACE PROCEDURE insertEMPLOYEE(
   e_id IN EMPLOYEE.EMPLOYEE_ID%TYPE,
   e_name IN EMPLOYEE.NAME%TYPE,
   e_salary IN EMPLOYEE.SALARY%TYPE)
IS
BEGIN

  INSERT INTO EMPLOYEE ("EMPLOYEE_ID", "NAME", "SALARY") 
  VALUES (e_id, e_name, e_salary);

  COMMIT;

END;

你可以使用 executeBatch() 来做你想做的事。例子:

Connection conn = null;
CallableStatement callableStatement = null;
String proc = "{call insertEMPLOYEE(?,?,?)}";
try{            
    //get connection
    conn = JDBCUtil.getConnection();

    //create callableStatement
    callableStatement = conn.prepareCall(proc);

    callableStatement.setInt(1, 7);
    callableStatement.setString(2, "Harish Yadav");
    callableStatement.setInt(3, 50000);
    callableStatement.addBatch();

    callableStatement.setInt(1, 8);
    callableStatement.setString(2, "Abhishek Rathor");
    callableStatement.setInt(3, 50000);
    callableStatement.addBatch();

    //execute query
    callableStatement.executeBatch();

    //close connection
    callableStatement.close();
    conn.close();

     System.out.println("Records inserted successfully.");
}catch(Exception e){
    e.printStackTrace();
}
于 2019-03-12T07:16:04.187 回答
2

您可以使用executeBatch(). 看这个例子

注意:我没有通过在本地运行来验证示例,但根据文档它应该可以工作。

于 2012-12-19T21:54:40.513 回答