I need to execute a set of statements which uses user-defined variables using 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. I stored the above statements in a Java string and tried to execute in the following way.
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?