JAVA INSERT INTO SELECT,可能吗?

问题描述 投票:0回答:2

是否可以使用NamedParameterJdbcTemplate进行“ INSERT INTO SELECT”?我想这样做,因为我有很多列都不会使用,所以我认为使用select会更容易。

有可能吗?

@Override
    public void insertIntoSelect(SomeDTO some) {
        try {
            StringBuilder sql = new StringBuilder();
            sql.append("INSERT INTO ");
            sql.append("    EXAMPLE_DB ");
            sql.append("SELECT ");
            sql.append("    COLUMN1, ");
            sql.append("    COLUMN2, ");
            sql.append("    COLUMN3, ");
            sql.append("    :testParam, ");
            sql.append("    COLUMN5, ");
            sql.append("FROM ");
            sql.append("    EXAMPLE_DB ");
            sql.append("WHERE ");
            sql.append("    COLUMN1 = :firstParam ");
            sql.append("    AND COLUMN2 = :secondParam ");

            MapSqlParameterSource param = new MapSqlParameterSource();
            param.addValue("firstParam", some.getSomeData());
            param.addValue("secondParam", some.getSomeDataTwo());
            param.addValue("testParam", some.getTestParam());

            new NamedParameterJdbcTemplate(dataSource).update(sql.toString(), param);
        } catch (BadSqlGrammarException e) {
            LOGGER.error("Example Error." + e);
            throw new BadSqlGrammarException(e);
        }
    }
java sql jdbc
2个回答
0
投票

[进行INSERT且仅使用某些列时,您需要将INSERT部分中的这些列列出为

StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO ");
        sql.append("    EXAMPLE_DB (");
        sql.append("    COLUMN1, ");
        sql.append("    COLUMN2, ");
        sql.append("    COLUMN3, ");
        sql.append("    some_column, "); <-- Proper column name needed here!!!
        sql.append("    COLUMN5) ");
        sql.append("SELECT ");
        sql.append("    COLUMN1, ");
        sql.append("    COLUMN2, ");
        sql.append("    COLUMN3, ");
        sql.append("    :testParam, ");
        sql.append("    COLUMN5 ");
        sql.append("FROM ");
        sql.append("    EXAMPLE_DB ");
        sql.append("WHERE ");
        sql.append("    COLUMN1 = :firstParam ");
        sql.append("    AND COLUMN2 = :secondParam ");

-1
投票

我认为您不能将参数用作列名。相反,您可以像StringBuilder这样修改,例如

String testParam = some.getTestParam();
StringBuilder sql = new StringBuilder();
         sql.append("INSERT INTO ");
         sql.append("    EXAMPLE_DB ");
         sql.append("SELECT ");
         sql.append("    COLUMN1, ");
         sql.append("    COLUMN2, ");
         sql.append("    COLUMN3, ");
         sql.append("   " + testParam + ",");
         sql.append("    COLUMN5, ");
         sql.append("FROM ");
         sql.append("    EXAMPLE_DB ");
         sql.append("WHERE ");
         sql.append("    COLUMN1 = :firstParam ");
         sql.append("    AND COLUMN2 = :secondParam ");

sql.append(“” + testParam +“,”);替换sql.append(“:testParam,”);可以工作]

© www.soinside.com 2019 - 2024. All rights reserved.