[英]remotely connecting oracle database with java
我試圖弄清楚如何遠程連接到 oracle 數據庫,以便從中獲取信息/數據。 我不知道如何 go 關於它的步驟。 我還想使用數據源連接 oracle DB。 我對此完全陌生,如果要問的不是太多,我可以逐步了解如何做到這一點。 我正在使用自由服務器。
我所做的只是通過互聯網閱讀可以回答我的查詢的內容,但我似乎無法找到我正在尋找的內容。 以下是我所擁有的,我正試圖從我所擁有的中了解如何實現我的目標。
在這種情況下,我想使用數據源並與 oracle DB 遠程連接。
package com.dBconnect;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DatabaseUtility {
private static DataSource dataSource;
static Connection conn;
public static void main(String ars[]) {
try {
conn = dataSource.getConnection();
System.out.println("connection established");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
您的示例代碼是一個獨立的 Java 程序,盡管您也使用 websphere-liberty 標記了該問題。 從獨立的 Java 程序與在應用程序服務器中運行時(后者)獲取數據源有不同的方法。
這是在 Liberty 中實現它的方法。
編輯服務器配置 (server.xml) 文件以啟用 jdbc 功能之一,
<featureManager>
<feature>jdbc-4.2</feature>
<feature>jndi-1.0</feature> <!-- for JNDI lookup of the data source -->
<feature>servlet-4.0</feature> <!-- or other features that you want to use -->
</featureManager>
<dataSource id="myDataSource" jndiName="jdbc/myOracleDataSource">
<jdbcDriver libraryRef="OracleLib"/>
<properties.oracle URL="jdbc:oracle:thin:@//localhost:1521/SAMPLEDB" user="user1" password="password1"/>
</dataSource>
<library id="OracleLib">
<file name="C:/Oracle/lib/ojdbc8.jar"/>
</library>
有關數據源配置的更多信息,請參閱此知識中心頁面上的示例配置。
從 web 或 ejb 組件(這里使用 servlet),使用資源注入如下(這不需要 jndi-1.0 特性),
@WebServlet("/*")
public class ExampleServlet extends javax.servlet.http.HttpServlet {
@Resource(lookup = "jdbc/myOracleDataSource")
private DataSource dataSource;
public void init() throws ServletException {
// Here is another way of accessing the data source - via JNDI lookup.
// This requires the jndi-1.0 feature
DataSource anotherDataSource = InitialContext.doLookup("jdbc/myOracleDataSource");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
conn = dataSource.getConnection();
System.out.println("connection established");
response.getWriter().println("connection established");
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("failed to establish connection: " + e);
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.