---
title: "java连接Oracle数据库"
author: "书安然"
date: "2015-01-15T21:14:16Z"
tags: []
categories: ["数据库"]
slug: "java-oracle"
draft: false
lastmod: "2015-01-15T21:14:16Z"
id: 2176359
url: "https://amflytogether.iteye.com/blog/2176359"
---

1.加载jdbc的jar包，可ojdbc6.jar/ojdbc14_g.jar
2.创建一个类
3.创建一个方法，用来连接数据库
public void getConnection(){
	Connection conn = null;//连接对象
		PreparedStatement psmt = null; //预编译
		ResultSet rs = null;//结果集
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");// 加载Oracle驱动
			conn = DriverManager.getConnection(
					"jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");//连接数据库
			String sql="select * from EMP where ename like ?";//sql语句
			//System.out.println("连接是否为空"+conn==null);
			psmt=conn.prepareStatement(sql);
			psmt.setString(1, "%K");//为问号赋值，从1开始
			rs=psmt.executeQuery();
			System.out.println("结果集是否为空："+(rs==null));
			while(rs.next()){
				System.out.println(rs.getInt("empno"));//rs.getXxx("列名");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(conn!=null){
					conn.close();
				}
				if(psmt!=null){
					psmt.close();
				}
				if(rs!=null){
					rs.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		

}