Mysql - 使用JDBC语句或preparedstatement执行查询集

时间:2015-04-24 19:44:39

标签: java mysql jdbc pivot dynamicquery

我需要执行一组使用jdbc使用用户定义变量的语句。 以下是我的询问:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(pa.fieldname = ''',
      fieldname,
      ''', pa.fieldvalue, NULL)) AS ',
      fieldname
    )
  ) INTO @sql
FROM product_additional;

SET @sql = CONCAT('SELECT p.id
                    , p.name
                    , p.description, ', @sql, ' 
                   FROM product p
                   LEFT JOIN product_additional AS pa 
                    ON p.id = pa.id
                   GROUP BY p.id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

我想用某种方法使用JDBC执行上述语句。我将上述语句存储在java字符串中,并尝试按以下方式执行。

 String sqlString = //above statements
 Statement stmt = connection.prepareStatement(sqlString);
 System.out.println("executing query ***************************");
 ResultSet rs = stmt.executeQuery(sql);

但它会引发以下错误。

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT
  GROUP_CONCAT(DISTINCT
               CONCAT(
                   'IF(cv.' at line 2

仅供参考,上述查询是将行数据转换为列数据(数据透视功能)。

有没有办法使用jdbc mysql执行上述查询?

2 个答案:

答案 0 :(得分:0)

根据我的理解,你不能选择像你在mysql中尝试的变量。

select
  *
into 
 @variable
from
  my_existing_table

如果要选择临时表,则必须手动创建。如下所示。

CREATE TEMPORARY TABLE IF NOT EXISTS my_temp_table AS (SELECT * FROM my_existing_table)

答案 1 :(得分:-2)

stmt.executeUpdate("SET @sql = NULL");
...
stmt.executeUpdate("PREPARE stmt FROM @sql");
stmt.executeQuery("EXECUTE stmt");
stmt.executeUpdate("DEALLOCATE PREPARE stmt");