我是 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;
}