JDBC代码规范化

 

public void func3() throws Exception {
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            // 得到连接
            String driverClassName = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/student";
            String username = "root";
            String password = "123";

            Class.forName(driverClassName);
            con = DriverManager.getConnection(url, username, password);// 实例化
            // 创建Statement
            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("name") + "," + rs.getInt("age")+","+rs.getString("gender"));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (con != null)
                con.close();
        }
    }

 

posted @ 2018-08-16 20:34  cmlx  阅读(184)  评论(0)    收藏  举报