java连接oracle数据库(常用数据库连接四)

1.确定安装好oracle数据库,用户名:scott 密码:tiger登录数据库建立一张表,内容如下:


2,eclipse或Myeclipse中建立工程并导入java连接oracle的jar包jdbc-oracle.jar,下载地址:http://download.csdn.net/detail/whzhaochao/6414981

3.建立iConn接口,代码如下:

package com.zhaochao.dba;

import java.sql.Connection;
public interface iConn {
	Connection getConn();
}

4.建立连接oracle数据库类实现iConn接口,代码如下:

注意修改数据库名,用户名和密码

package com.zhaochao.dba;

import java.sql.Connection;
import java.sql.DriverManager;

public class OrcaleConn implements iConn {
	
	
	private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver" ;
	private static final String DBURL = "jdbc:oracle:thin:@127.0.0.1:1521:ORCL" ;
	private static final String DBUSER = "scott" ;
	private static final String DBPASS = "tiger";
	private Connection conn=null;
	@Override
	public Connection getConn() {
		// TODO Auto-generated method stub
		
		try {
			Class.forName(DBDRIVER);
			this.conn=DriverManager.getConnection(DBURL, DBUSER, DBPASS);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return this.conn;

	}

}

5.测试连接

package com.zhaochao.dba;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	//	TestMySQL();
		TestOracle();	
	//	TestDB2();
	//	TestSQLServer();
	//	TestAccess();
		
	}

	
	
	private static void TestOracle() {
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		iConn iconn=new OrcaleConn();
		conn=iconn.getConn();
		String sql="select * from zhaochao";
		
		try {
			System.out.println("asdfasf");
			ps=conn.prepareStatement(sql);
			rs=ps.executeQuery();
			while(rs.next()){
				System.out.println(rs.getString(1)+"|"+rs.getString(2)+"|"+rs.getString(3));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(conn!=null){
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(ps!=null){
				try {
					ps.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(rs!=null){
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
	

6.测试结果:

asdfasf
1|admin|admin
2|zhaochao|zhaochao


posted @ 2013-10-18 16:58  赵侠客  阅读(206)  评论(0编辑  收藏  举报