java代码连接oracle的DBUtil代码

在java代码连接oracle数据库的时候要导入架包,下载oracle软件的时候,已经自带了oraclesl.jar,只需把它从安装的盘内build path 进来即可,具体操作省略。

package com.money.dbutil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
      //连接对象(用于创建数据库连接)
	static Connection conn=null;
	static Statement state=null;//用于对数据进行操作
	static ResultSet rs=null;//结果集(用于获取数据查询)
	
	//jdbc:oracle:thin:	表示通过JDBC连接oracle数据库的通讯协议
	//@localhost:		表示连接的主机[服务器]
	//1521:				表示主机上的程序端口
	//orcl				表示程序端口上的数据库
	static String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl";

	static String user="money";//登陆oracle的登录名
	static String password="123";//登陆oracle
	//静态块[将数据了连接驱动使用反射机制加载至JVM]
	static{
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
		}catch(ClassNotFoundException e){
			System.out.println("驱动加载失败");
			e.printStackTrace();
		}
	}
	//创建打开数据库连接的方法
	public static void openConnection(){
		try{
			 conn=DriverManager.getConnection(url,user,password);
		}catch(SQLException e){
			System.out.println("数据库连接失败");
			e.printStackTrace();
		}
	}
	//创建关闭数据库的方法,后创建的对象先关闭
	public static void closeConnection(){
	   try{
		   if(rs!=null){
			   rs.close();
		   }
	   }catch(SQLException e){
		   rs=null;
	   }finally{
		   try{
		     if(state!=null){
		    	 state.close();
		     }   
		   }catch(SQLException e){
			   state=null;
		   }finally{
				try{
					if(conn!=null){
						conn.close();
					}
				}catch(SQLException e){
					conn=null;
				}
			}
	   }
	}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值