log4jdbc 使用入门

阅读更多

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.运行结果:


log4jdbc 使用入门_第1张图片

3.项目配置:

 


log4jdbc 使用入门_第2张图片

4.过滤日志:

   
   
   
   
   

 

5. over

 

 

  • log4jdbc 使用入门_第3张图片
  • 大小: 68.3 KB
  • log4jdbc 使用入门_第4张图片
  • 大小: 27.7 KB
  • 查看图片附件

你可能感兴趣的:(log4jdbc 使用入门)