java代码连接oracle的DBUtil代码

来源:互联网 发布:2017网络机顶盒哪个好 编辑:程序博客网 时间:2024/06/05 21:57

在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("com.microsoft.sqlserver.jdbc.SQLServerDriver");        }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;                }            }       }    }
原创粉丝点击