Advertisement
Guest User

Untitled

a guest
Aug 3rd, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. package mysql;
  2.  
  3. import java.sql.*;
  4.  
  5. public class ProductsMainApp {
  6.  
  7. private static final String SELECT_PRODUCTS_QUERY =
  8. "SELECT * FROM products";
  9.  
  10. public static void main(String[] args){
  11. String url = "jdbc:mysql://localhost:3306/products_ex";
  12. try(Connection connection = getConnection(url);
  13. PreparedStatement preparedStatement =
  14. connection.prepareStatement(SELECT_PRODUCTS_QUERY);
  15. ResultSet resultSet = preparedStatement.executeQuery()){
  16.  
  17. while (resultSet.next()){
  18. int id = resultSet.getInt("id");
  19. String name = resultSet.getString("name");
  20. String description = cutDescription(resultSet.getString("description"));
  21. double price = resultSet.getDouble("price");
  22. System.out.println(String.format("Product: id:%d, name:%s," +
  23. " description:%s, price:%f", id, name, description, price));
  24. }
  25.  
  26. } catch (SQLException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30.  
  31. private static String cutDescription(String description){
  32. if(description.length() > 20){
  33. return description.substring(0,20) + "...";
  34. }else{
  35. return description;
  36. }
  37. }
  38.  
  39. private static Connection getConnection(String url) throws SQLException {
  40. return DriverManager.getConnection(url,"root", "root");
  41. }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement