Java连接Oracle基础应用:
1.Eclipse新建一个Java项目:OracleConnection
2.添加驱动文件到项目资源中,驱动文件在:
[Oracle安装路径]product11.2.0dbhome_1jdbclib 中找到。 文件名:ojdbc6.jar
3.新建一个Java类:OracleConnectionTest.java
代码如下:
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement;public class OracleConnectionTest {private String url="jdbc:oracle:thin:@127.0.0.1:1521:YOOTK";private String dbUsername="SCOTT";private String dbPassword="tiger";//注意要引入java.sql.Connection 而不是util包下的private Connection conn=null;private Statement statement=null;private ResultSet rs=null;private String sql="";public void selectTest(){try { Class.forName("oracle.jdbc.OracleDriver"); conn=DriverManager.getConnection(url, dbUsername, dbPassword); sql="select * from emp"; statement=conn.createStatement(); rs=statement.executeQuery(sql);while(rs.next()){ System.out.println(rs.getString(1));}} catch (Exception e) { e.printStackTrace();}finally {try {if(rs==null){ rs.close();}if(statement==null){ statement.close();}if(conn==null){ conn.close();}} catch (Exception e2) {// TODO: handle exception e2.printStackTrace();}}}public static void main(String[] args) {new OracleConnectionTest().selectTest();}}
运行成功,控制台输出数据库EMP表第一列的所有值。