eclipse如何连接oracle 11g数据库
1.首先先建立一个项目DB,右键点击DB,选择Build Path-->Configure Build Path进入
通过Add External JARs..选择D:\orcl\app\hr\product\11.2.0\dbhome_1\owb\wf\lib下的ojdbc14.jar,点击ok。
2.编写ConnectOracle.java文件
package com.wuy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectOracle {
private Connection con;
private String user="scott";
//private String user = "sys as sysdba";
private String password="18233188050";
private String className="oracle.jdbc.driver.OracleDriver";
//private String url="jdbc:oracle:oci@localhost:1158:orcl";这个url可能无效
private String url = "jdbc:oracle:thin:@hr-PC:1521:orcl";hr-PC和1521很关键,也就是侦听串里有没有这个,在
D:\orcl\app\hr\product\11.2.0\dbhome_1\NETWORK\ADMIN\tnsnames.ora这个文件里有没有,一定要根据tnsnames.ora这个文件来配置url路径,否则会出错!!!
public ConnectOracle(){
try{
Class.forName(className);
System.out.println("加载数据库驱动成功!");
}catch(ClassNotFoundException e){
System.out.println("加载数据库驱动失败!");
e.printStackTrace();
}
}
/**创建数据库连接*/
public Connection getCon(){
try {
con=DriverManager.getConnection(url,user,password);
System.out.println("创建数据库连接成功!");
} catch (SQLException e) {
System.out.print(con);
System.out.println("创建数据库连接失败!");
con=null;
e.printStackTrace();
}
return con;
}
public void closed(){
try{
if(con!=null){
con.close();
}
}catch(SQLException e){
System.out.println("关闭con对象失败!");
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectOracle c=new ConnectOracle();
c.getCon();
c.closed();
}
}
3.运行结果: