1

您好 下面是我为使用 JDBC 连接连接到 Oracle DB 并返回一些值而编写的代码。但是如果我在我的机器上打开 oracle toad,这段代码会建立连接并返回结果。

但是当 oracle toad 关闭并尝试运行这段代码时,它不会连接。

请让我知道如何在不手动打开 oracle toad 的情况下连接到 oracle DB。

package library;
import java.io.IOException;
import java.sql.*;

public class DBAutomationConnection {
public static void main(String args[]) throws ClassNotFoundException, IOException, SQLException {
  DBAutomationConnection dbconn = new DBAutomationConnection();
  //Connection conn = dbconn.DBConnection1();
  dbconn.DBConnection1("select * from employee where empid='test123'","ROLE_NAME");

}

public void DBConnection1(String query, String colName)throws IOException, ClassNotFoundException{
 Connection connection = null;
 Statement stmt = null;
  try {
      // Load the JDBC driver

      String driverName = "oracle.jdbc.driver.OracleDriver";

      Class.forName(driverName);

      connection = DriverManager.getConnection("jdbc:oracle:thin:@//testhostname:1528/ServiceName", "XXAAA_U", "Jw9S");
      System.out.println("Connection successful: " +connection);


      try {
              stmt = connection.createStatement();
              ResultSet rs = stmt.executeQuery(query);
              while (rs.next()) {
                    //String UserID = rs.getString("USER_ID");
                  String UserID = rs.getString(colName);
                    System.out.println(UserID);     
              }
        } catch (SQLException e ) {
              System.out.println("Could not execute query.");
              //JDBCTutorialUtilities.printSQLException(e);
        } finally {
              if (stmt != null) { stmt.close(); }
        }


  } catch (SQLException e) {
                  System.out.println("Could not connect to the database");
  }

}
4

3 回答 3

1

您应该从您的操作系统设置>服务初始化 Oracle TNS-Listener 服务。您可能需要检查您的 tns 配置。

于 2013-02-13T10:04:34.323 回答
0

您的系统中是否安装了 Oracle Thin 驱动程序?这个链接可以指导你。

于 2013-02-13T10:30:30.070 回答
0

您需要在系统中安装 ORACLE 客户端才能远程连接 oracle。

http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html

于 2013-02-13T10:28:31.933 回答