码迷,mamicode.com
首页 > 数据库 > 详细

Java通用oracle数据库连接

时间:2017-09-28 13:03:47      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:red   name   dstat   date()   用户   res   for   ++   pwd   

Java中oracle数据库连接写一个通用类UBUtil(){}

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    private static Connection con;
    private static String url;
    private static String user;
    private static String pwd;

    public DBUtil() {

    }
    static {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            InputStream is = DBUtil.class.getResourceAsStream("/db.properties");//db.properties 是一个用户配置文件传用户名密码
            Properties prop=new Properties();
            prop.load(is);
            url=prop.getProperty("url");
            user=prop.getProperty("user");
            pwd=prop.getProperty("password");
            con = DriverManager.getConnection(url, user, pwd);
        }catch (Exception e){
        }
    }
    public static ResultSet find(String sql){
        con=getCon();
        try {
            Statement smt=con.createStatement();
            ResultSet rs=smt.executeQuery(sql);
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static ResultSet find(String sql,Object ...pram){//...pram数组
        con=getCon();
        try {
            PreparedStatement smt=con.prepareStatement(sql);
            for (int i=0;i<pram.length;i++){
                smt.setObject(i+1,pram[i]);
            }
            ResultSet rs=smt.executeQuery();
            return rs;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void insert(String sql,Object ...pram){//...pram数组
        con=getCon();
        try {
            PreparedStatement smt=con.prepareStatement(sql);
            for (int i=0;i<pram.length;i++){
                smt.setObject(i+1,pram[i]);
            }
            smt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static Connection getCon(){
        try {
            if(con==null||con.isClosed())
                con = DriverManager.getConnection(url, user, pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
}

 

Java通用oracle数据库连接

标签:red   name   dstat   date()   用户   res   for   ++   pwd   

原文地址:http://www.cnblogs.com/feipengting/p/7606042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!