[英]ClassNotFoundException: oracle.jdbc.OracleDriver
[英]Register oracle.jdbc.OracleDriver
我是Java Web服务的新手。 我玩了几天,终于可以连接到另一台机器上的Oracle数据库了。 到目前为止开心。
到目前为止,我在网上看到的样本都说您只需要注册一次oracle.jdbc.OracleDriver。
您如何在网络服务上做到这一点? 现在,每次调用getUserFullName之类的函数时,我都会对其进行注册。
任何输入表示赞赏。
编辑:这是功能之一:
public static String getUserName(int id) throws SQLException {
String returnValue = "";
Statement stmt = null;
ResultSet rset = null;
Connection conn = null;
try {
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
conn = DriverManager.getConnection("jdbc:oracle:thin:@//myOracleIP:1521/myOracleDB", "admin", "password");
stmt = conn.createStatement();
rset = stmt.executeQuery("select name from tbl_users where id = " + id);
while(rset.next()) {
returnValue = rset.getString("name");
}
}
catch(Exception ex) {
returnValue = "jdbc.getUserName -- Exception: " + ex.getMessage();
}
finally {
// close resultset
if(rset != null)
if(!rset.isClosed())
rset.close();
// close statement
if(stmt != null)
if(!stmt.isClosed())
stmt.close();
// close connection
if(conn != null)
if(!conn.isClosed())
conn.close();
}
stmt = null;
rset = null;
conn = null;
return returnValue;
}
JNDI功能
public static String getNameWithJNDI(int id) throws SQLException {
int statusCode = 0;
String returnValue = "Open DB";
DataSource dc = null;
Statement stmt = null;
ResultSet rset = null;
Connection conn = null;
Context context = null;
try {
context = new InitialContext();
// my datasource from the GlassFish
dc = (DataSource)context.lookup("jdbc/myConnection");
context.close();
}
catch(NamingException e) {
statusCode = 1;
returnValue = "jdbc.GetNameWithJNDI - InitialContext Error: " + e.getMessage();
}
if((statusCode == 0) && (dc != null)) {
try {
conn = dc.getConnection();
stmt = conn.createStatement();
rset = stmt.executeQuery("select name from tbl_users where id = " + id);
if(rset != null) {
while(rset.next()) {
returnValue = "JNDI: " + rset.getString("name");
}
}
}
catch(SQLException e) {
statusCode = 1;
returnValue = "jdbc.GetNameWithJNDI - Database Error: " + e.getMessage();
}
finally {
// close resultset
if(rset != null)
if(!rset.isClosed())
rset.close();
// close statement
if(stmt != null)
if(!stmt.isClosed())
stmt.close();
// close connection
if(conn != null)
if(!conn.isClosed())
conn.close();
}
}
dc = null;
stmt = null;
rset = null;
conn = null;
context = null;
return returnValue;
}
不需要注册符合JDBC 4的驱动程序。 如果使用的是应用程序服务器,通常的方法是在应用程序服务器中创建一个DataSource
,然后在应用程序中使用它(通过使用JNDI进行引用),而不是使用DriverManager
创建连接。 应用程序服务器DataSource
通常还负责诸如连接池之类的事情。
每当需要使用JDBC资源时,我都会使用JNDI查找,尤其是当您使用的是Java Application Server(看起来像是在进行Web服务)时。 这意味着您不必每次都一直加载JDBC驱动程序。 例如,您可能想看看以下内容: http : //docs.oracle.com/cd/A97335_02/apps.102/a83724/samapp9.htm
连接池也可以在以下文章中找到: http : //www.eclipse.org/jetty/documentation/current/jndi-datasource-examples.html#pooling-datasources
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.