简体   繁体   English

如何从Java连接中获取查询字符串?

[英]How to get query string from connection in Java?

I'm writing a method that tries to log db calls, form connecting to it, to after the query, there are many places that calls the method connect() to start and the cleanUp() method to end, I can't and don't want to modify every place.我正在编写一个尝试记录数据库调用、连接到它的表单的方法,在查询之后,有很多地方调用方法 connect() 开始和调用 cleanUp() 方法结束,我不能和不想修改每个地方。 So the sequence is like this :所以顺序是这样的:

  Connection con = ...
  connect();
  s = con.createStatement();
  ResultSet rs = s.executeQuery(" select * from xyz ");
  rs.next();
  cleanUp();

There are many methods that uses this sequence, so how do I, somehow in cleanUp(), get the sql query string [ in this case : select * from xyz ] from all the methods that run their queries, is there a way to get that info from the "con", does the con object know what query it has just ran ?有很多方法使用这个序列,那么我如何在 cleanUp() 中以某种方式从运行其查询的所有方法中获取 sql 查询字符串 [在这种情况下:select * from xyz ],有没有办法获得来自“con”的信息,con 对象是否知道它刚刚运行了什么查询?

I suggest to you to use an aspect, AspectJ would be perfect for this case.我建议您使用方面,AspectJ 非常适合这种情况。 With an aspect, you could trigger a behavior once your monitored method has been executed.一方面,一旦执行了受监视的方法,您就可以触发行为。 Here are a couple examples you could check: http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html and https://mathewjhall.wordpress.com/2011/03/31/tracing-java-method-execution-with-aspectj/以下是您可以查看的几个示例: http : //www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.htmlhttps://mathewjhall.wordpress.com/2011/03 /31/tracing-java-method-execution-with-aspectj/

您可以在 MySQL 中从Statement.toString()获取它。

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

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