Advertisement
sergAccount

Untitled

Apr 4th, 2021
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.41 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6. package com.spec.service;
  7.  
  8. import java.util.List;
  9. import com.spec.model.Person;
  10. import com.spec.util.DataBaseUtil;
  11. import java.sql.Connection;
  12. import java.sql.PreparedStatement;
  13. import java.sql.ResultSet;
  14. import java.util.ArrayList;
  15.  
  16. public class ProductService {
  17.     // CRUD - операции С - create, R - read, U - update, D - delete
  18.  
  19.     //R - read
  20.     // метод для получения объектов типа Person
  21.     // select * from person
  22.     public List<Person> getAll() throws Exception {
  23.         String sql = "select * from person";
  24.         List<Person> persons = new ArrayList<>();
  25.         try (Connection c = DataBaseUtil.getConnection();
  26.                 PreparedStatement st = c.prepareStatement(sql);
  27.                 ResultSet rs = st.executeQuery()) {
  28.             // испольуем метод next - для перемещения по записям
  29.             while (rs.next()) {
  30.                 long personId = rs.getLong("id");
  31.                 String name = rs.getString("name");
  32.                 System.out.println("personId=" + personId);
  33.                 System.out.println("name=" + name);
  34.                 persons.add(new Person(personId, name));
  35.             }
  36.         }
  37.         return persons;
  38.     }
  39.  
  40.     // select * from person where id = ?
  41.     // select * from person where id = ? and name = ?
  42.     // нумерация параметров производится с 1
  43.     public Person getPerson(long id) throws Exception {
  44.         String sql = "select * from person where id = ?";
  45.         Person p = null;
  46.         try (Connection c = DataBaseUtil.getConnection();
  47.                 PreparedStatement st = c.prepareStatement(sql)) {
  48.             // подстановка параметра (нумерация параметров производится с 1 )
  49.             st.setLong(1, id);
  50.             ResultSet rs = st.executeQuery();
  51.             // испольуем метод next - для перемещения по записям
  52.             if (rs.next()) {
  53.                 long personId = rs.getLong("id");
  54.                 String name = rs.getString("name");
  55.                 p = new Person(personId, name);
  56.             }
  57.         }
  58.         return p;
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement