-
Notifications
You must be signed in to change notification settings - Fork 11
Базы данных #15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lepfel
wants to merge
3
commits into
iaulitin:master
Choose a base branch
from
lepfel:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Базы данных #15
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package ru.milandr.courses.pavlyuk; | ||
|
|
||
| public class CompAppl { | ||
| public static void main(String[] args) { | ||
| boolean comparisonResult = CompDatabase.compareData("jdbc:postgresql://localhost:5432/users_database", | ||
| "jdbc:postgresql://localhost:5432/users_database2", | ||
| "users", | ||
| "users", | ||
| "id,last_name"); | ||
| System.out.println(comparisonResult); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| package ru.milandr.courses.pavlyuk; | ||
|
|
||
| import java.sql.*; | ||
|
|
||
| import java.util.*; | ||
| import java.util.stream.IntStream; | ||
|
|
||
| public class CompDatabase { | ||
|
|
||
|
|
||
| public static boolean compareData(String db1Link, | ||
| String db2Link, | ||
| String table1Name, | ||
| String table2Name, | ||
| String columns) { | ||
|
|
||
| HashMap<String, List<String>> table1 = new HashMap<>(); | ||
|
|
||
| HashMap<String, List<String>> table2 = new HashMap<>(); | ||
| List<String> requestedColumns = Arrays.asList(columns.split(",")); | ||
|
|
||
|
|
||
| requestedColumns.forEach(col -> { | ||
| table1.put(col, new ArrayList<>()); | ||
| table2.put(col, new ArrayList<>()); | ||
| }); | ||
|
|
||
| try (Connection con = DriverManager.getConnection(db1Link, | ||
| "postgres", "postgres"); | ||
| Connection con2 = DriverManager.getConnection(db2Link, | ||
| "postgres", "postgres"); | ||
| Statement smt = con.createStatement( | ||
| ResultSet.TYPE_SCROLL_SENSITIVE, | ||
| ResultSet.CONCUR_READ_ONLY); | ||
| Statement smt2 = con2.createStatement( | ||
| ResultSet.TYPE_SCROLL_SENSITIVE, | ||
| ResultSet.CONCUR_READ_ONLY)) { | ||
| Class.forName("org.postgresql.Driver"); | ||
|
|
||
| ResultSet rs = smt.executeQuery("SELECT " + columns + " FROM " + table1Name); | ||
| ResultSet rs2 = smt2.executeQuery("SELECT " + columns + " FROM " + table2Name); | ||
|
|
||
| rs.last(); | ||
| int numberOfRowsTable1 = rs.getRow(); | ||
|
|
||
| rs2.last(); | ||
| int numberOfRowsTable2 = rs2.getRow(); | ||
|
|
||
| if (numberOfRowsTable1 != numberOfRowsTable2) { | ||
| return false; | ||
| } | ||
|
|
||
| if (numberOfRowsTable1 == 0) { | ||
| return true; | ||
| } | ||
|
|
||
| IntStream stream = IntStream.range(1, numberOfRowsTable1 + 1); | ||
| stream.forEach(e -> requestedColumns | ||
| .forEach(col -> { | ||
| try { | ||
| rs.absolute(e); | ||
| rs2.absolute(e); | ||
| table1.get(col).add(rs.getString(col)); | ||
| table2.get(col).add(rs2.getString(col)); | ||
| } catch (SQLException ex) { | ||
| ex.printStackTrace(); | ||
| System.out.println("Введенные колонки не найдены"); | ||
| System.exit(0); | ||
| } | ||
| })); | ||
| } catch (SQLException | ClassNotFoundException e) { | ||
| e.printStackTrace(); | ||
|
|
||
| System.out.println("Проблема при работе с БД!"); | ||
| System.exit(0); | ||
| } | ||
|
|
||
| return (table1.equals(table2)); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| package ru.milandr.courses.pavlyuk; | ||
|
|
||
| import java.sql.*; | ||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| public class HomeTask4 { | ||
| public static void main(String[] args) { | ||
|
|
||
| try (Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/users_database", | ||
| "postgres", "postgres"); | ||
| Statement smt = con.createStatement()) { | ||
| Class.forName("org.postgresql.Driver"); | ||
|
|
||
| // 1. Найти средствами джавы (!) пользователя с наибольшим id. | ||
| // Просто найти пользователя по условию id = 100 не будет считаться решением. | ||
| // Вывести всю информацию о нем в консоль. | ||
|
|
||
| HomeTask4Methods.method1(smt); | ||
|
|
||
| //2. Вывести всех пользователей, проживающих по адресу P.O. Box 677, 8665 Ante Road. | ||
| // Для того, чтобы это сделать необходимо самостоятельно освоить такую SQL-конструкцию как JOIN. | ||
|
|
||
| HomeTask4Methods.method2(smt); | ||
|
|
||
| //3. Вывести всех пользователей, отсортировав их средствами джавы (!) в алфавитном порядке по их фамилии. | ||
|
|
||
| HomeTask4Methods.method3(smt); | ||
|
|
||
|
|
||
| // 4. Найти средствами джавы (!) среднее значение почтового индекса, учитывая только числовые значения индекса. | ||
|
|
||
| HomeTask4Methods.method4(smt); | ||
|
|
||
| //5. Найти адрес, по которому не проживает ни один пользователь. | ||
| // Для того, чтобы это сделать необходимо самостоятельно освоить такую SQL-конструкцию как JOIN | ||
|
|
||
| HomeTask4Methods.method5(smt); | ||
|
|
||
| } catch (SQLException | ClassNotFoundException e) { | ||
| e.printStackTrace(); | ||
|
|
||
| System.out.println("Проблема при работе с БД!"); | ||
| System.exit(0); | ||
| } | ||
| } | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| package ru.milandr.courses.pavlyuk; | ||
|
|
||
| import java.sql.*; | ||
| import java.util.ArrayList; | ||
| import java.util.Collections; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| public class HomeTask4Methods { | ||
|
|
||
| /** | ||
| * Создает коллекцию из объектов класса Users по переданным полям из таблицы users базы данных users_database. | ||
| * | ||
| * @param rs множетсва результатов данных, полученных в результате SQL – запроса. | ||
| * @return коллекция из объектов класса Users, полученная после обработки результата rs. | ||
| * @throws SQLException Может возникнуть при вызове метода selectAllData. | ||
| */ | ||
| private static List<User> selectAllData(ResultSet rs) throws SQLException { | ||
| List<User> users = new ArrayList<>(); | ||
| while (rs.next()) { | ||
| User user = new User(rs.getInt("id"), rs.getString("first_name"), | ||
| rs.getString("last_name"), rs.getInt("address_id"), | ||
| rs.getString("phone_number")); | ||
| users.add(user); | ||
| } | ||
| return users; | ||
| } | ||
|
|
||
| /** | ||
| * Находит в таблице users пользователя c наибольшим id и выводит всю информацию о нем. | ||
| * | ||
| * @param smt объект типа Statement, служащий для исполнения запросов к базе данных users_database. | ||
| * @throws SQLException Может возникнуть при вызове метода selectAllData. | ||
| */ | ||
| public static void method1(Statement smt) throws SQLException { | ||
| ResultSet rs = smt.executeQuery("SELECT * FROM users;"); | ||
| List<User> users = selectAllData(rs); | ||
| System.out.println(Collections.max(users, Comparator.comparing(User::getId))); | ||
| } | ||
|
|
||
| /** | ||
| * Находит в таблице users всех пользователей, проживающих по адресу P.O. Box 677, 8665 Ante Road и выводит. | ||
| * | ||
| * @param smt объект типа Statement, служащий для исполнения запросов к базе данных users_database. | ||
| * @throws SQLException Может возникнуть при вызове метода selectAllData. | ||
| */ | ||
| public static void method2(Statement smt) throws SQLException { | ||
| ResultSet rs = smt.executeQuery("SELECT * " + | ||
| "FROM users INNER JOIN addresses " + | ||
| "ON users.address_id = addresses.id " + | ||
| "WHERE address = 'P.O. Box 677, 8665 Ante Road';"); | ||
| List<User> usersLivingAtAnteRoad = selectAllData(rs); | ||
| System.out.println(usersLivingAtAnteRoad.toString()); | ||
| } | ||
|
|
||
| /** | ||
| * Сортирует в алфавитном порядке по фамилии пользователей из таблицы users и выводит. | ||
| * | ||
| * @param smt объект типа Statement, служащий для исполнения запросов к базе данных users_database. | ||
| * @throws SQLException Может возникнуть при вызове метода selectAllData. | ||
| */ | ||
| public static void method3(Statement smt) throws SQLException { | ||
| ResultSet rs = smt.executeQuery("SELECT * FROM users;"); | ||
| List<User> users = selectAllData(rs); | ||
|
|
||
| users.sort(Comparator.comparing(User::getLastName)); | ||
| System.out.println(users.toString()); | ||
| } | ||
|
|
||
| /** | ||
| * Находит в таблице users среднее значение почтового индекса. | ||
| * | ||
| * @param smt объект типа Statement, служащий для исполнения запросов к базе данных users_database. | ||
| * @throws SQLException Может возникнуть при вызове метода selectAllData. | ||
| */ | ||
| public static void method4(Statement smt) throws SQLException { | ||
| Double averageAddress; | ||
| ResultSet rs = smt.executeQuery("SELECT * FROM users;"); | ||
| List<User> users = selectAllData(rs); | ||
|
|
||
| averageAddress = users.stream().collect(Collectors.averagingDouble(User::getAddressId)); | ||
| System.out.println(averageAddress); | ||
| } | ||
|
|
||
| /** | ||
| * Находит в базе данных users_database адрес из таблицы addresses, по которому не проживает ни один пользователь из таблицы users. | ||
| * | ||
| * @param smt объект типа Statement, служащий для исполнения запросов к базе данных users_database. | ||
| * @throws SQLException Может возникнуть при вызове метода selectAllData. | ||
| */ | ||
| public static void method5(Statement smt) throws SQLException { | ||
| String addressWithoutUser = null; | ||
| ResultSet rs = smt.executeQuery("SELECT address " + | ||
| "FROM users RIGHT JOIN addresses " + | ||
| "ON users.address_id = addresses.id " + | ||
| "WHERE first_name is NULL;"); | ||
| while (rs.next()) { | ||
| addressWithoutUser = rs.getString(1); | ||
| } | ||
| System.out.println(addressWithoutUser == null ? "null" : addressWithoutUser); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| package ru.milandr.courses.pavlyuk; | ||
|
|
||
| public class User { | ||
| private int id; | ||
| private String firstName; | ||
| private String lastName; | ||
| private int addressId; | ||
| private String phoneNumber; | ||
|
|
||
| public User(int id, String firstName, String lastName, int addressId, String phoneNumber) { | ||
| this.id = id; | ||
| this.firstName = firstName; | ||
| this.lastName = lastName; | ||
| this.addressId = addressId; | ||
| this.phoneNumber = phoneNumber; | ||
| } | ||
|
|
||
| public int getId() { | ||
| return id; | ||
| } | ||
|
|
||
| public String getFirstName() { | ||
| return firstName; | ||
| } | ||
|
|
||
| public String getLastName() { | ||
| return lastName; | ||
| } | ||
|
|
||
| public int getAddressId() { | ||
| return addressId; | ||
| } | ||
|
|
||
| public String getPhoneNumber() { | ||
| return phoneNumber; | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "User{" + | ||
| "id='" + id + '\'' + | ||
| ", firstName='" + firstName + '\'' + | ||
| ", lastName='" + lastName + '\'' + | ||
| ", addressId='" + addressId + '\'' + | ||
| ", phoneNumber='" + phoneNumber + '\'' + | ||
| '}'; | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.