Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mysql;
- import java.sql.*;
- public class ProductsMainApp {
- private static final String SELECT_PRODUCTS_QUERY =
- "SELECT * FROM products";
- public static void main(String[] args){
- String url = "jdbc:mysql://localhost:3306/products_ex";
- try(Connection connection = getConnection(url);
- PreparedStatement preparedStatement =
- connection.prepareStatement(SELECT_PRODUCTS_QUERY);
- ResultSet resultSet = preparedStatement.executeQuery()){
- while (resultSet.next()){
- int id = resultSet.getInt("id");
- String name = resultSet.getString("name");
- String description = cutDescription(resultSet.getString("description"));
- double price = resultSet.getDouble("price");
- System.out.println(String.format("Product: id:%d, name:%s," +
- " description:%s, price:%f", id, name, description, price));
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- private static String cutDescription(String description){
- if(description.length() > 20){
- return description.substring(0,20) + "...";
- }else{
- return description;
- }
- }
- private static Connection getConnection(String url) throws SQLException {
- return DriverManager.getConnection(url,"root", "root");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement