Advertisement
Guest User

Untitled

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