如何在内部sql stament中使用预准备语句?

时间:2017-03-10 10:36:09

标签: java sql jdbc prepared-statement

执行此操作时,会抛出以下异常, "您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以便在' SELECT travel_manager_id FROM travel_agency_manager附近使用正确的语法WHERE user_id =(SELECT user_i' at line 1"

公共类AgencyRegistrationDAOImpl扩展了DBConnection {

public int registerAgency(Agency agency) throws SQLException {

    int returnVal = 0;
    Connection connection = getConnection();

        if (connection != null) {

            String query = "INSERT INTO travel_agency (agency_manager_id,trade_name," +
        "company_name,address,email,city,district,tpno,web_link,description,agency_image_link,business_registration_number" +
        ",isApproved) VALUES " +
        "(SELECT travel_manager_id FROM travel_agency_manager WHERE user_id=(SELECT user_id FROM users WHERE email=?)),?,?,?,?,?,?,?,?,?,?,?,?)";


            returnVal = CRUDOperations.insertAsPreparedStmt(query, connection, agency.getUserName(), agency.getTradeName(),
                    agency.getCompanyName(),  agency.getAddress(), agency.getEmail(), agency.getCity(),
                    agency.getDistrict(), agency.getTelePhoneNumber(), agency.getWeblink(), agency.getDescription(),
                    agency.getImagePath(), agency.getRegistration(), 0);

        }

    return returnVal;
}

}

公共类CRUDOperations {

public static int insertAsPreparedStmt(String query, Connection connection, Object... values) throws SQLException {

    PreparedStatement preparedStatement = null;
    try {

        if (connection != null) {
            preparedStatement = connection.prepareStatement(query);

            for (int index = 0; index < values.length; index++) {
                preparedStatement.setObject(index + 1, values[index]);
            }
            return preparedStatement.executeUpdate();
        }

    } finally {
        if (!connection.isClosed() && !preparedStatement.isClosed()) {
            preparedStatement.close();
            connection.close();
        }
    }
    return 0;
}

}

1 个答案:

答案 0 :(得分:0)

  

您的SQL语法错误

这不是正确的语法

INSERT INTO ... VALUES SELECT ....

正确的语法是

INSERT INTO ... SELECT ...

以下是mysql doc

INSERT INTO travel_agency (
            agency_manager_id,trade_name, company_name,address,email,city,district,tpno,web_link,description,agency_image_link,business_registration_number, isApproved
    ) 
    SELECT travel_manager_id,?,?,?,?,?,?,?,?,?,?,?,?
            FROM travel_agency_manager WHERE user_id=
            (
                SELECT user_id FROM users WHERE email=?
            )