3

I want to remove the duplicate records from mysql db. And tried below query which will do as expected by manually. But I just want to execute this from JDBC, but It throws exception.

Query:

 CREATE TABLE tests(
 test_name VARCHAR(50),
 product_id int);

   // duplicate record insert
 INSERT INTO tests VALUES('WALLET_01',25);
 INSERT INTO tests VALUES('WALLET_01',25);


  // The below code will remove the duplicate from table
 SET @sql = NULL;
 SET @Rn = NULL;
 SELECT
 (COUNT(*)-1) 
 INTO @Rn
 FROM tests
 WHERE test_name='WALLET_01' AND product_id=25;


 SET @sql = CONCAT('DELETE FROM tests WHERE test_name=''WALLET_01'' AND 
 product_id=25 limit ',@Rn);

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

I just execute this query through JDBC as below:

  String query="SET @sql = NULL; SET @Rn = NULL; SELECT(COUNT(*)-1) INTO @Rn FROM tests WHERE test_name='WALLET_01' AND product_id=25;SET @sql = CONCAT('DELETE FROM tests WHERE test_name=''WALLET_01'' AND product_id=25 limit ',@Rn);PREPARE stmt FROM @sql;EXECUTE stmt;DEALLOCATE PREPARE stmt;";

  connection = DBConnectionUtils.getConnection().createNewConnection();
  this.statement = connection.createStatement();
  this.result = statement.executeQuery(query);

Executed the above code throws syntax exception as below. But It works fine manually.

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 'SET @Rn = NULL; SELECT(COUNT(*)-1) INTO @Rn FROM tests WHERE test_name='PWBAR-Fu' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2497)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2455)
    at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1369)

Any leads?

ArrchanaMohan
  • 2,314
  • 4
  • 36
  • 84

0 Answers0