日期:2014-05-19 浏览次数:20655 次
package com;
import java.sql.*;
import javax.sql.*;
public class Test {
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
//1。注册驱动
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//2。通过驱动管理器建立连接
String url = "jdbc:oracle:thin:@192.168.0.106:1521:dylanfire";
String dbUsername = "scott";
String dbPassword = "dylan";
conn = DriverManager.getConnection(url, dbUsername, dbPassword);
//3.建立连接对象
stmt = conn.createStatement();
//4、通过对象传递数据,并返回结果
String sql = "select ename, job, sal, hiredate from emp";
rs = stmt.executeQuery(sql);
while(rs.next()){
String ename = rs.getString("ename");
String job = rs.getString("job");
Double sal = rs.getDouble("sal");
java.sql.Date hiredate = rs.getDate("hiredate");
System.out.println(ename + ", " + job + ", " + sal + ", " + hiredate);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
oracle服务器的server-name是dylanfire
192.168.0.106是局域网安装oracle数据库的IP。
我通过telnet可以访问到oracle的数据库
不知道为什么通过JAVA就不可以
eclipse给出的异常为:
java.sql.SQLException: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:451)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:535)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:218)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:29)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:528)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.Test.main(Test.java:21)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:356)