使用准备好的语句插入多行

时间:2018-08-02 19:49:08

标签: mysql prepared-statement sql-insert

我正在尝试使用准备好的语句查询在表中插入多行。我需要从第二个表中检索2个值,并将它们与3个参数一起插入。

MySQL仅将子查询视为单个值,而不是检索到的2,因此由于只有四个,因此要求添加另一个参数。

public class AccountServiceBeanTest {


    private static final String URI_BASE = "http://localhost:8080/app/rest/v2";
    private static final String CLIENT_ID = "client";
    private static final String Client_SECRET = "secret";
    private String oathToken;

    @ClassRule
    public static MyappTestContainer cont = MyappTestContainer.Common.INSTANCE;
    private Metadata metadata;
    private Persistence persistence;
    private DataManager dataManager;

    private User mockUser;

    @Before
    public void setUp() throws Exception {

        oathToken = getAuthToken("admin","password");
        metadata = cont.metadata();
        persistence = cont.persistence();
        dataManager = AppBeans.get(DataManager.class);

 String methodName = "myapp_AccountService/createUser/";
        String url = "/services/" + methodName;
        String userId;
        String firstname = "Test First Name";
        String lastname = "Test Last Name";

        String json = "{\"firstname\": \" "  + firstname + " \" , \"lastname\": \" "  + lastname + " \", \"district\": { \"dcode\": \"029\" } }";

        try (CloseableHttpResponse response = sendPost(url, oathToken, jsonr)) {

            ReadContext resultPh =  parseResponse(response);
            userId = resultPh.read("$.id");
        }

        UUID idUser = UUID.fromString(userId);
        String methodName = "myapp_AccountService/assignUser/";
        String url = "/services/" + methodName;
        UUID id;
        String emailAddress = "testMyapp@myappTests.ca";

        String json = "{\"userId\":  " +userId + ", \"emailAddress\": \"" + emailAddress + "\" }";


        try (CloseableHttpResponse response = sendPost(url, oathToken, json)) {

            ReadContext result = parseResponse(response);
            id = UUID.fromString(result.read("$.id"));
            Transaction tx = persistence.createTransaction();
            EntityManager em = persistence.getEntityManager();
            User user = em.find(User.class,id, new View(User.class).addProperty("email"));
            tx.commit();

    } } 

1 个答案:

答案 0 :(得分:1)

您需要插入INSERT ... SELECT形式,而不是INSERT ... VALUES()形式。

INSERT INTO tbl_permit_daily_sign_off 
            (permit_id, shift, employee_id, sign_off_date, type)
     SELECT tbl_permit_project.permit_id, tbl_shifts.shift_name  
      FROM tbl_permit_project
INNER JOIN tbl_shifts ON tbl_permit_project.project_id = tbl_shifts.project_id
     WHERE tbl_shifts.end_time <= NOW()), ?, ?, ?)

这是如何工作的?

1)设计一个SELECT查询,提供要在INSERT查询中使用的列。然后您对其进行测试并进行故障排除。

2)您将INSERT INTO tbl (col, col, col...)放在SELECT之前。

您的INSERT选择(permit_id, shift, employee_id, sign_off_date, type)列,但是您的SELECT仅提及其中两列。您需要SELECT才能提及全部五个。