简体   繁体   English

使用 JDBC Statement 或 PreparedStatement 执行一组查询

[英]Executing set of queries using JDBC Statement or PreparedStatement

I need to execute a set of statements which uses user-defined variables using JDBC.我需要使用 JDBC 执行一组使用用户定义变量的语句。

Below is my query:以下是我的查询:

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;

I want some way to execute the above statements using JDBC.我想要某种方式使用 JDBC 执行上述语句。 I stored the above statements in a Java string and tried to execute in the following way.我将上述语句存储在 Java 字符串中,并尝试按以下方式执行。

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

But it throws the below error.但它会引发以下错误。

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

FYI, the above query is to convert row data into columnar data (pivot functionality).仅供参考,上述查询是将行数据转换为列数据(枢轴功能)。

Is there a way to execute the above query using JDBC and MySQL?有没有办法使用 JDBC 和 MySQL 执行上述查询?

From my understanding you can't select into a variable like you are trying in mysql.根据我的理解,您无法像在 mysql 中尝试那样选择变量。

select
  *
into 
 @variable
from
  my_existing_table

If you want to select into a temporary table you have to create it manually.如果要选择到临时表中,则必须手动创建它。 Like below.像下面。

CREATE TEMPORARY TABLE IF NOT EXISTS my_temp_table AS (SELECT * FROM my_existing_table)
stmt.executeUpdate("SET @sql = NULL");
...
stmt.executeUpdate("PREPARE stmt FROM @sql");
stmt.executeQuery("EXECUTE stmt");
stmt.executeUpdate("DEALLOCATE PREPARE stmt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM