Thursday, May 22, 2008

How to log sql statement stored in PreparedStatement



Take the following program.

import java.net.URL;
import java.sql.*;

class JDBCapp {
static MyConnection theConn;

public static void main (String args[]) {
new JDBCapp().doit();
}

public void doit() {
theConn = new MyConnection();
theConn.connect("EAS Demo DB V3", "dba", "sql");

PreparedStatement prepstmt;
try {
prepstmt = theConn.dbConn.prepareStatement
("SELECT emp_id FROM employee" );
prepstmt.execute();
prepstmt.close();
}
catch (Exception e) { e.printStackTrace(); }
theConn.disconnect();
}
}


class MyConnection {
Connection dbConn = null;
void connect(String db, String user, String passw) {
try {
Driver d =
(Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String URL = "jdbc:odbc:" + db;
dbConn = DriverManager.getConnection(URL, user, passw);
java.io.PrintWriter w =
new java.io.PrintWriter
(new java.io.OutputStreamWriter(System.out));
DriverManager.setLogWriter(w);

}
catch (Exception e) {
e.printStackTrace();
}
}

void disconnect() {
try {
dbConn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}


If we use BasicDataSource to getConnection instead of DriverManager,
use BasicDataSource .setLogWriter.

In addition, to log these sql strings to log4j, we will redirect these messages from printwriter to log4j. Use the following code to do this.

http://www.cenqua.com/clover/eg/jboss/report/org/jboss/logging/util/LoggerWriter.html

No comments:

Google