Skip to content

Commit

Permalink
split the method createTable into two
Browse files Browse the repository at this point in the history
  • Loading branch information
Vlad committed May 3, 2024
1 parent d4a807d commit 15b36f1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 15 deletions.
32 changes: 18 additions & 14 deletions src/main/java/mate/academy/DatabaseInitializer.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,30 @@
import mate.academy.exception.DataProcessingException;

public class DatabaseInitializer {
private static final String FILE_PATH = "src/main/resources/init_db.sql";

public void createTable() {
try (Connection connection = ConnectionUtil.getConnection();
Statement statement = connection.createStatement()) {
StringBuilder sqlCommands = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new FileReader("src/main/resources/init_db.sql"))) {
String line;
while ((line = reader.readLine()) != null) {
sqlCommands.append(line).append(" ");
}
} catch (IOException e) {
throw new DataProcessingException("Failed to read init_id.sql file: ", e);
}

statement.executeUpdate(sqlCommands.toString());
String sqlCommands = parseCommandFile(FILE_PATH);
statement.executeUpdate(sqlCommands);
System.out.println("Table created successfully.");
} catch (SQLException e) {
throw new DataProcessingException("Failed to create table", e);
}
}
}


private String parseCommandFile(String filePath) {
StringBuilder sqlCommands = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
sqlCommands.append(line.trim()).append("\n");
}
} catch (IOException e) {
throw new DataProcessingException("Failed to read init_id.sql file: " + filePath, e);
}
return sqlCommands.toString();
}
}
7 changes: 6 additions & 1 deletion src/main/resources/init_db.sql
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
CREATE TABLE `books` (`id` BIGINT NOT NULL AUTO_INCREMENT, `title` VARCHAR(255), `price` INT, PRIMARY KEY (`id`));
CREATE TABLE `books` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(255),
`price` INT,
PRIMARY KEY (`id`)
);

0 comments on commit 15b36f1

Please sign in to comment.