JDBC基礎(三)

優化上期代碼

針對查詢語句示例:

	/**
     * 優化
     */
    @Test
    public void selectDBpro() {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "950404");
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from user ");
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                int age = resultSet.getInt("age");
                String name = resultSet.getString("name");
                System.out.println("id:" + id + "," + "age:" + age + "," + "name:" + name + "");
            }
            //不用的東西需要關閉
            resultSet.close();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //一旦不用,必須關閉連接的資源
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章