Hi下面是我为使用JDBC连接连接到Oracle DB而编写的代码并返回一些值。但是如果我在我的机器中打开oracle toad,这段代码会建立连接并返回结果。
但是当oracle toad关闭并尝试运行此代码时,它将无法连接。
请让我知道如何连接oracle DB并手动打开oracle toad。
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");
}
}
答案 0 :(得分:1)
您应该从操作系统设置>服务初始化Oracle TNS-Listener Service。您可能需要检查您的tns配置。
答案 1 :(得分:0)
您需要在系统中安装ORACLE客户端以远程连接oracle。
http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
答案 2 :(得分:0)
您的系统中是否安装了Oracle Thin驱动程序?这个link可以指导您。