JAVA-JDBC的封装

是不是每次在写jdbc的时候,链接参数跟驱动加载什么的写的很头痛,来封装自己的jdbc吧!
  思路:
1、将链接参数使用properties文件保存!!!注意哟
2、使用properties类读取链接参数,这样以后修改链接的数据库,不用修改源码文件
3、使用静态代码块读取参数,提高效率
4、封装获取connection对象的方法
5、封装statement对象的方法
6、preparedStatement方法 
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;




public class TestJdbc {
    //声明参数
    private static String driver="";
    private static String url="";
    private static String user="";
    private static String pwd="";
    //使用静态代码块 类加载的时候就会被执行,执行一次
    static{
        Properties pt=new Properties();
        try {
            //pt.load(SxtJdbc.class.getClassLoader().getResourceAsStream("com\\bsjxt\\prepare\\sxtjdbc.properties"));
            pt.load(SxtJdbc.class.getClassLoader().getResourceAsStream("myjdbc.properties"));
            driver=pt.getProperty("driver");
            url=pt.getProperty("url");
            user=pt.getProperty("user");
            pwd=pt.getProperty("pwd");
            System.out.println(driver+"-"+url+"-"+user+"-"+pwd);
            Class.forName(driver);//加载驱动
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //封装自己的获取connection方法
    public static Connection getConnection(){
        Connection conn=null;
        try {
          conn=DriverManager.getConnection(url, user, pwd);
        } catch (SQLException e) {
            System.err.println("链接参数异常:"+"["+url+"],"+"["+user+"],"+"["+pwd+"]");
            e.printStackTrace();
        }
        return conn;
    }

    //获取statement对象
    public static Statement getStatemenct(Connection conn){
        Statement stmt=null;

        try {
            stmt=conn.createStatement();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        return stmt;    
    }


    //封装preproties对象
    public static PreparedStatement getPreparedStatment(Connection conn,String sql){
        PreparedStatement ps=null;
        try {
            ps= conn.prepareStatement(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ps;
    }
}
myjdbc.properties文件中参数列表
driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
user=test
pwd=1234
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值