不能打印sql,那么开发调试又需要sql,怎么办呢?
容器化后,可以修改环境上的jdbc.properties:
jdbc.url后面加?statementInterceptors=MySQLStatementInterceptor
例如:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://10.146.200.243:3306/monalarmdb?statementInterceptors=MySQLStatementInterceptor
jdbc.username=root
jdbc.password=root
将附件中的class解压放入WEB-INF/classes目录下。
这样,开启INFO级别日志,会打印出每条发送给mysql驱动执行的sql语句。
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.ResultSetInternalMethods;
import com.mysql.jdbc.Statement;
import com.mysql.jdbc.StatementInterceptorV2;
public class MySQLStatementInterceptor implements StatementInterceptorV2
{
private ThreadLocal timeHolder = new ThreadLocal();
@Override
public void destroy()
{
}
@Override
public boolean executeTopLevelOnly()
{
return true;
}
@Override
public void init(Connection arg0, Properties arg1) throws SQLException
{
// System.out.println("init sql:" + arg0);
}
@Override
public ResultSetInternalMethods postProcess(String arg0, Statement arg1, ResultSetInternalMethods arg2,
Connection arg3, int arg4, boolean arg5, boolean arg6, SQLException arg7) throws SQLException
{
Long useTime = System.currentTimeMillis() - timeHolder.get();
String sql = getSql(arg1);
if (StringUtils.isNotEmpty(sql))
{
System.out.println("post sql:" + sql + "use time:" + useTime + "ms");
if (null != arg7)
{
System.out.println("catch exception " + arg7.getClass().getName() + ":" + arg7.getMessage());
}
}
return null;
}
@Override
public ResultSetInternalMethods preProcess(String arg0, Statement arg1, Connection arg2) throws SQLException
{
// String sql = getSql(arg1);
// if (StringUtils.isNotEmpty(sql))
// {
// System.out.println("pre sql:" + sql);
// }
timeHolder.set(System.currentTimeMillis());
return null;
}
private String getSql(Statement arg1)
{
String sql = null;
if (arg1 instanceof PreparedStatement)
{
try
{
sql = ((PreparedStatement)arg1).asSql();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return sql;
}
}