浏览 2515 次
锁定老帖子 主题:log4jdbc 使用入门
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-10-21
log4jdbc 可以将占位符与参数全部合并在一起显示,方便直接拷贝 sql 在 PLSQL Developer 等客户端直接执行,加快调试速度. 记录执行的sql及其耗时等.
1.测试代码
package com.mtea.demo.test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Demo { private static Logger logger = LoggerFactory.getLogger(Demo.class); public static void main(String args[]) { test_without_log4jdbc_effect(); test_with_log4jdbc_effect(); } /** * no log4jdbc */ public static void test_without_log4jdbc_effect(){ //mysql-connector-java-5.1.10-bin.jar提供的类 String driverNameOfMysql = "com.mysql.jdbc.Driver"; String connStringOfMysql = "jdbc:mysql://localhost:3306/db_hibernate"; Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; try { Class.forName(driverNameOfMysql); conn = DriverManager.getConnection(connStringOfMysql, "root", "root"); pstmt = conn.prepareStatement("select name from tb_product where id=?"); pstmt.setInt(1, 1); rs=pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString("name")); } rs.close(); } catch (Exception e) { logger.error("test_without_log4jdbc_effect 出错", e); } finally { logger.info("test_without_log4jdbc_effect finished"); } } /** * with log4jdbc_effect */ public static void test_with_log4jdbc_effect(){ //log4jdbc4-1.2beta2.jar提供的类 String driverName = "net.sf.log4jdbc.DriverSpy"; String connString = "jdbc:log4jdbc:mysql://localhost:3306/db_hibernate"; Connection conn = null; ResultSet rs = null; PreparedStatement pstmt = null; try { Class.forName(driverName); conn = DriverManager.getConnection(connString, "root", "root"); pstmt = conn.prepareStatement("select name from tb_product where id=?"); pstmt.setInt(1, 1); rs=pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString("name")); } rs.close(); } catch (Exception e) { logger.error("test_with_log4jdbc_effect 出错", e); } finally { logger.info("test_with_log4jdbc_effect finished"); } } } 2.运行结果: 3.项目配置:
4.过滤日志: <logger name="jdbc.connection" level="ERROR"/>
5. over
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |