阿里Java学习路线:阶段 2:数据库开发-JDBC数据库开发入门:课时4:JDBC之代码规范化

规范化代码

所谓规范化代码就是无论是否出现异常, 都要关闭 ResultSet, Statement 以及 Connection,如果你还记得IO流的规范化代码,那么下面的代码你就明白什么意思了。

示例:

public void query() {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null; // 在try外给出引用的定义
     
        try{
            con = getConnection(); // 在try内为对象实例化
            stmt = con.createStatement();
            String sql = "SELECT * FROM user";
            rs = stmt.executeQuery(sql);
     
            while(rs.next()){
                String username = rs.getString(1); // 获取第一列的值, 参数为列编号或列名
                String password = rs.getString(2); // 获取第二列的值
                System.out.println(username+","+password);
            }
        } catch(Exception e){
            throw new RuntimeException(e);
        } finally{
            try{
                if(rs != null) rs.close();
                if(stmt != null) stmt.close();
                if(con != null) con.close(); // 在finally中进行关闭
            } catch(SQLException e){
                throw new RuntimeException(e);
            }
        }

测试类:

    @Test
    public void fun3() throws Exception{
    	Connection con = null; // 定义引用
    	Statement stmt = null;
    	ResultSet rs = null;
    	try {
	    	/*
	    	 * 一、得到连接
	    	 */
			String driverClassName = "com.mysql.jdbc.Driver";
			String url = "jdbc:mysql://localhost:3306/mydb1?characterEncoding=utf8&useSSL=true";
			String username = "root";
			String password = "1234";
			
			Class.forName(driverClassName);
			con = DriverManager.getConnection(url,username,password); // 实例化
			
			/*
			 * 二、创建Statment
			 */
			stmt = con.createStatement();
			String sql = "SELECT * FROM emp";
    		rs = stmt.executeQuery(sql);
    		/*
    		 * 三、循环遍历rs,打印其中数据
    		 * getString()和getObject()是通用的
    		 */
    		while(rs.next()) {
    			System.out.println(rs.getObject(1) + "," + rs.getString("ename") + "," + rs.getDouble("sal"));
    		}
    	} catch (Exception e) {
    		throw new RuntimeException(e);
		} finally {
			// 关闭
            if(rs != null) rs.close();
            if(stmt != null) stmt.close();
            if(con != null) con.close();
		}
    }

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值