【问题标题】:Create table as select with parameter using jdbcTemplate使用 jdbcTemplate 创建表作为带参数的选择
【发布时间】:2021-11-08 16:43:53
【问题描述】:

我想使用 jdbcTemplate 根据条件创建基于另一个表的表。我有 postgres 数据库。当我执行这个并传递参数时:

String SQL = "create table test as (select * from users where countryId =?)";


jdbcTemplate.update(SQL, new Object[] {3})

我收到了包含 users 表中所有列但没有行的表测试。

但是,当我执行此操作时:

String SQL = "create table test as (select * from users where countryId =3)";


jdbcTemplate.update(SQL)

我收到了带有 countryId = 3 行的测试表,这就是我期望在第一个解决方案中收到的内容。

【问题讨论】:

  • 试试jdbcTemplate.update(SQL, 3)
  • 我怀疑您是否可以将参数与CREATE TABLE AS SELECT 一起使用。将其拆分为CREATE TABLEINSERT

标签: java spring postgresql jdbc jdbctemplate


【解决方案1】:

您传递的绑定变量不正确,但它没有起到任何作用。

你简单的不能数据定义语句中使用绑定变量正如你在触发错误中立即看到的那样

Caught: org.springframework.jdbc.UncategorizedSQLException: 
PreparedStatementCallback; uncategorized SQLException for SQL 
[create table test as (select * from users where countryId =?)];
 SQL state [72000]; error code [1027]; 
ORA-01027: bind variables not allowed for data definition operations

所以你有两个选择,要么连接语句(不推荐这样做,因为有SQL注入的危险)

或将语句分成两部分:

// create empty table
sql = "create table test as (select * from users where 1 = 0)";
jdbcTemplate.update(sql) 

// insert data
sql = "insert into test(countryId, name)  select countryId, name from users where countryId =?";
updCnt = jdbcTemplate.update(sql, new SqlParameterValue(Types.INTEGER,3));

请注意,在insert 语句中,您可以看到将3 的整数值作为绑定变量传递的正确方式。

【讨论】:

    【解决方案2】:

    您也可以遵循以下方法:-

    jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS employee_tmp (id INT NOT NULL)");

    List<Object[]> employeeIds = new ArrayList<>();
    for (Integer id : ids) {
        employeeIds.add(new Object[] { id });
    }
    jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds);
    

    这里你可以使用2个操作来查询以避免SQL注入。

    【讨论】:

      【解决方案3】:

      您以错误的方式使用来自jdbcTemplate 的方法update

      试试这个:

      String SQL = "create table test as (select * from users where countryId = ?)";
      jdbcTemplate.update(SQL, 3);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-24
        • 1970-01-01
        • 1970-01-01
        • 2015-08-30
        • 2018-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多