Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package com.spec.service;
- import java.util.List;
- import com.spec.model.Person;
- import com.spec.util.DataBaseUtil;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.util.ArrayList;
- public class ProductService {
- // CRUD - операции С - create, R - read, U - update, D - delete
- //R - read
- // метод для получения объектов типа Person
- // select * from person
- public List<Person> getAll() throws Exception {
- String sql = "select * from person";
- List<Person> persons = new ArrayList<>();
- try (Connection c = DataBaseUtil.getConnection();
- PreparedStatement st = c.prepareStatement(sql);
- ResultSet rs = st.executeQuery()) {
- // испольуем метод next - для перемещения по записям
- while (rs.next()) {
- long personId = rs.getLong("id");
- String name = rs.getString("name");
- System.out.println("personId=" + personId);
- System.out.println("name=" + name);
- persons.add(new Person(personId, name));
- }
- }
- return persons;
- }
- // select * from person where id = ?
- // select * from person where id = ? and name = ?
- // нумерация параметров производится с 1
- public Person getPerson(long id) throws Exception {
- String sql = "select * from person where id = ?";
- Person p = null;
- try (Connection c = DataBaseUtil.getConnection();
- PreparedStatement st = c.prepareStatement(sql)) {
- // подстановка параметра (нумерация параметров производится с 1 )
- st.setLong(1, id);
- ResultSet rs = st.executeQuery();
- // испольуем метод next - для перемещения по записям
- if (rs.next()) {
- long personId = rs.getLong("id");
- String name = rs.getString("name");
- p = new Person(personId, name);
- }
- }
- return p;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement