彻底封装JDBC操作MySQL的连接。

只需3步。

1、导入mysql的jar包。

2、封装配置文件db.properties

driverClass = com.mysql.jdbc.Driver            
url = jdbc:mysql:///databaseName?useUnicode=true&characterEncoding=utf8
user = root
password = 123
把数据库驱动和一些数据库参数封装到配置文件,做到随时更换数据库。

3、封装连接代码

/**
 * Created by youxuan on 2017/1/15 0015.
 * JDBC工具类
 */
public class JDBCUtil  {
    private static final String driverClass;
    private static final String url;
    private static final String user;
    private static final String password;


    static {


        try {
            InputStream in  = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties pr = new Properties();
            pr.load(in);

            driverClass = pr.getProperty("driverClass");
            url = pr.getProperty("url");
            user = pr.getProperty("user");
            password = pr.getProperty("password");

            Class.forName(driverClass);

        } catch (Exception e) {
           throw new ExceptionInInitializerError(e);
        }
    }


    public static Connection getConnection() throws SQLException {

        Connection conn = DriverManager.getConnection(url,user,password);
        return conn;
    }

    /**
     *	清理数据库资源 
     * @param rs
     * @param stat
     * @param conn
     */
    public static void  release(ResultSet rs, Statement stat,Connection conn){

        try {

            if (rs != null) {
                rs.close();
            }
            rs = null;

            if(stat != null){
                stat.close();
            }
            stat = null;

            if(conn!=null){
                conn.close();
            }

            conn = null;

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}


4、连接测试

          public void text1(){
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		
		try{
			conn = JDBCUtil.getConnection();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(" select * from user ");
			while(rs.next()){
				.......
			}
		
		}catch(Exception e){
			throw new RuntimeException(e);
		}finally{
			JDBCUtil.release(rs, stmt, conn); //关闭数据库资源
		}
	}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值