Advertisement
Guest User

Untitled

a guest
May 28th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. private List<City> getCities() {
  2.         final String driver = "com.mysql.jdbc.Driver";
  3.         try {
  4.             Class.forName(driver);
  5.         } catch (ClassNotFoundException e) {
  6.             e.printStackTrace();
  7.         }
  8.  
  9.         List<City> cityList = null;
  10.         final String dbPath = "jdbc:mysql://localhost:3306/world";
  11.         final String sqlQuery = "SELECT Name, Population FROM city";
  12.         Connection conn = null;
  13.         Statement statement = null;
  14.         ResultSet resultSet = null;
  15.         try {
  16.             conn = DriverManager.getConnection(dbPath, "root", "admin");
  17.             statement = conn.createStatement();
  18.             resultSet = statement.executeQuery(sqlQuery);
  19.  
  20.             String cityName = null;
  21.             int cityPopulation = 0;
  22.             cityList = new ArrayList<>();
  23.             while (resultSet.next()) {
  24.                 cityName = resultSet.getString("Name");
  25.                 cityPopulation = resultSet.getInt("Population");
  26.                 City city = new City(cityName, cityPopulation);
  27.                 cityList.add(city);
  28.             }
  29.         } catch (SQLException e) {
  30.             e.printStackTrace();
  31.         } finally {
  32.             if (conn != null) {
  33.                 try {
  34.                     conn.close();
  35.                 } catch (SQLException e) {
  36.                     e.printStackTrace();
  37.                 }
  38.             }
  39.         }
  40.        
  41.         return cityList;
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement