我是 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
通常还负责连接池之类的事情。
关于java - 注册oracle.jdbc.OracleDriver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17173244/