Why JavaBean load jdbc driver failed?
In jsp, forName("sun.jdbc.odbc.JdbcOdbcDriver") run successfully. When
used in JavaBean,
forName will fail. While run JavaBean class directly, it works. Why?
The following is the code.
package com;
import java.io.*;
import java.util.*;
import java.sql.*;
public class Publisher {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Connection conn = null;
ResultSet rs = null;
public Publisher() {
}
public boolean open(String url, String user, String passwd) {
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, user, passwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public ResultSet executeQuery(String sql) {
if (conn == null) {
return null;
}
rs = null;
try {
Statement stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}
catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public void close() {
try {
rs.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Publisher pb = new Publisher();
pb.open("jdbc:odbc:Publisher", "user", "user");
ResultSet rs = pb.executeQuery("SELECT * FROM Publisher");
String id, name, url;
System.out.println("Publisher_ID Name URL");
try {
while (rs.next()) {
id = rs.getString("Publisher_ID");
name = rs.getString("name");
url = rs.getString("url");
System.out.println(id + " " + name + " " + url);
}
} catch (SQLException e) {
e.printStackTrace();
}
pb.close();
}
}
// !!!!!!!!!!!!!!!!!!!!!!!!! NOTE !!!!!!!!!!!!!!!!!!!!!!!!!!!
java com.Publisher // OK!
http://localhost:8080/publisher.jsp will report error for open(url,
user, passwd) return false;