JDBC规范

来源:互联网 发布:陈大可的知乎icm 编辑:程序博客网 时间:2024/05/17 23:35

JDBC需要做到的代码规范

void fun () throw Exception {   //这三个对象要在finally中关闭,所以要定义在try块外面    Connection conn = NULL ;    Statement stmt = NULL ;    ResultSet rs = NULL ;     try{            Class.forName("com.mysql.jdbc.Driver");            String url = "jdbc:mysql://localhost:3306/数据库名";            String username = "root";            String password = "123456";            conn = DriverManager.getConnection(url , username , password);            stmt = conn.createStatement();            String sql = "select * where people";            rs = stmt.excuteQuery(sql);            while(rs.next()){              system.out.println(rs.getObject(1)+","+...);        }    }catch(Exception e){                throw new RuntimeException (e) ;        } finally{            //关闭要倒着来关闭                  try {                    if(rs != null) rs.close();                    if(stmt != null) stmt.close();                    if(con != null) con.close();                }             catch(SQLException e) {            }    }}