使用JDBC编写复杂触发器,如何正确转义

时间:2014-09-28 14:39:11

标签: java mysql jdbc triggers

这是我在MySql WorkBench中编写的触发器,用于将新创建的行保存为json。

delimiter |

CREATE TRIGGER insert_movies AFTER INSERT ON movies
 FOR EACH ROW
 BEGIN
  SET @json = " { ";
  SET @json = CONCAT(@json,"\"","tableName","\"",":","\"","movies","\"",",");
  SET @json = CONCAT(@json,"\"","action","\"",":","\"","insert","\"",",");
  SET @json = CONCAT(@json,"\"","NewData","\"",":");
  SET @json = CONCAT(@json," { ");
  IF NEW.id is not null then
  SET @json = CONCAT(@json, "\"","ID","\"", ":", "\"",replace(NEW.id,'"','\\"'), "\"");
  END IF;
  if New.title is not null then 
  SET @json = CONCAT(@json, ",");
  SET @json = CONCAT(@json, "\"","TITLE","\"", ":", "\"",replace( NEW.title,'"','\\"'), "\"");
  END IF;
  SET @json = CONCAT(@json," } ");
  SET @json = CONCAT(@json, "}");
  INSERT INTO updated(d) values(@json);
END;

有效。但我想用JDBC来写这个。

 Connection con = ds.getConnection();
 Statement sm = con.createStatement();
 StringBuilder triBuilder = new StringBuilder();
 triBuilder.append("CREATE TRIGGER insert_movies");
 ....
 triBuilder.append(" CONCAT(@json,\"\\\"\","tableName",\"\\\"\",\":\",\"\\\"\","movies","\"",",") ");

我尝试过,但逃避的事情变得太复杂了,我无法让它发挥作用。请帮帮我。

0 个答案:

没有答案