-
Notifications
You must be signed in to change notification settings - Fork 53.8k
BAEL-4350: Difference between Statement and PreparedStatement #9645
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
Merged
Merged
Changes from all commits
Commits
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
23 changes: 23 additions & 0 deletions
23
...-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactory.java
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,23 @@ | ||
| package com.baeldung.statmentVsPreparedstatment; | ||
|
|
||
| import java.sql.Connection; | ||
| import java.sql.DriverManager; | ||
| import java.sql.SQLException; | ||
|
|
||
| public class DatasourceFactory { | ||
|
|
||
| private Connection connection; | ||
|
|
||
| public Connection getConnection() throws ClassNotFoundException, SQLException { | ||
| Class.forName("org.h2.Driver"); | ||
| connection = DriverManager.getConnection("jdbc:h2:mem:db_basic", "SA", ""); | ||
| connection.setAutoCommit(false); | ||
| return connection; | ||
| } | ||
|
|
||
| public boolean createTables() throws SQLException { | ||
| String query = "create table if not exists PERSONS (ID INT, NAME VARCHAR(45))"; | ||
| return connection.createStatement().executeUpdate(query) == 0; | ||
| } | ||
|
|
||
| } |
42 changes: 42 additions & 0 deletions
42
...-java-persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/PersonEntity.java
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,42 @@ | ||
| package com.baeldung.statmentVsPreparedstatment; | ||
|
|
||
| import java.util.Objects; | ||
|
|
||
| public class PersonEntity { | ||
| private int id; | ||
| private String name; | ||
|
|
||
| public PersonEntity(int id, String name) { | ||
| this.id = id; | ||
| this.name = name; | ||
| } | ||
|
|
||
| public int getId() { | ||
| return id; | ||
| } | ||
|
|
||
| public void setId(int id) { | ||
| this.id = id; | ||
| } | ||
|
|
||
| public String getName() { | ||
| return name; | ||
| } | ||
|
|
||
| public void setName(String name) { | ||
| this.name = name; | ||
| } | ||
|
|
||
| @Override public boolean equals(Object o) { | ||
| if (this == o) | ||
| return true; | ||
| if (o == null || getClass() != o.getClass()) | ||
| return false; | ||
| PersonEntity that = (PersonEntity) o; | ||
| return id == that.id && Objects.equals(name, that.name); | ||
| } | ||
|
|
||
| @Override public int hashCode() { | ||
| return Objects.hash(id, name); | ||
| } | ||
| } |
88 changes: 88 additions & 0 deletions
88
...nce/src/main/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDao.java
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,88 @@ | ||
| package com.baeldung.statmentVsPreparedstatment; | ||
|
|
||
| import java.sql.Connection; | ||
| import java.sql.PreparedStatement; | ||
| import java.sql.ResultSet; | ||
| import java.sql.SQLException; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
|
|
||
| public class PreparedStatementPersonDao { | ||
|
|
||
| private final Connection connection; | ||
|
|
||
| public PreparedStatementPersonDao(Connection connection) { | ||
| this.connection = connection; | ||
| } | ||
|
|
||
| public Optional<PersonEntity> getById(int id) throws SQLException { | ||
| String query = "SELECT id, name FROM persons WHERE id = ?"; | ||
|
|
||
| PreparedStatement preparedStatement = connection.prepareStatement(query); | ||
| preparedStatement.setInt(1, id); | ||
| ResultSet resultSet = preparedStatement.executeQuery(); | ||
|
|
||
| if (resultSet.first()) { | ||
|
|
||
| PersonEntity result = new PersonEntity(resultSet.getInt("id"), | ||
| resultSet.getString("name")); | ||
|
|
||
| return Optional.of(result); | ||
| } else { | ||
| return Optional.empty(); | ||
| } | ||
|
|
||
| } | ||
|
|
||
| public void insert(PersonEntity personEntity) throws SQLException { | ||
|
|
||
| String query = "INSERT INTO persons(id, name) VALUES( ?, ?)"; | ||
|
|
||
| PreparedStatement preparedStatement = connection.prepareStatement(query); | ||
| preparedStatement.setInt(1, personEntity.getId()); | ||
| preparedStatement.setString(2, personEntity.getName()); | ||
| preparedStatement.executeUpdate(); | ||
|
|
||
| } | ||
|
|
||
| public void insert(List<PersonEntity> personEntities) throws SQLException { | ||
| String query = "INSERT INTO persons(id, name) VALUES( ?, ?)"; | ||
|
|
||
| PreparedStatement preparedStatement = connection.prepareStatement(query); | ||
| for (PersonEntity personEntity : personEntities) { | ||
| preparedStatement.setInt(1, personEntity.getId()); | ||
| preparedStatement.setString(2, personEntity.getName()); | ||
| preparedStatement.addBatch(); | ||
| } | ||
| preparedStatement.executeBatch(); | ||
|
|
||
| } | ||
|
|
||
| public void update(PersonEntity personEntity) throws SQLException { | ||
| String query = "UPDATE persons SET name = ? WHERE id = ?"; | ||
| PreparedStatement preparedStatement = connection.prepareStatement(query); | ||
| preparedStatement.setString(1, personEntity.getName()); | ||
| preparedStatement.setInt(2, personEntity.getId()); | ||
| preparedStatement.executeUpdate(); | ||
| } | ||
|
|
||
| public void deleteById(int id) throws SQLException { | ||
| String query = "DELETE FROM persons WHERE id = ?"; | ||
| PreparedStatement preparedStatement = connection.prepareStatement(query); | ||
| preparedStatement.setInt(1, id); | ||
| preparedStatement.executeUpdate(); | ||
| } | ||
|
|
||
| public List<PersonEntity> getAll() throws SQLException { | ||
| String query = "SELECT id, name FROM persons"; | ||
|
|
||
| PreparedStatement preparedStatement = connection.prepareStatement(query); | ||
| ResultSet resultSet = preparedStatement.executeQuery(); | ||
| List<PersonEntity> result = new ArrayList<>(); | ||
| while (resultSet.next()) { | ||
| result.add(new PersonEntity(resultSet.getInt("id"), resultSet.getString("name"))); | ||
| } | ||
| return result; | ||
| } | ||
| } |
75 changes: 75 additions & 0 deletions
75
...persistence/src/main/java/com/baeldung/statmentVsPreparedstatment/StatementPersonDao.java
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,75 @@ | ||
| package com.baeldung.statmentVsPreparedstatment; | ||
|
|
||
| import java.sql.Connection; | ||
| import java.sql.ResultSet; | ||
| import java.sql.SQLException; | ||
| import java.sql.Statement; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
|
|
||
| public class StatementPersonDao { | ||
|
|
||
| private final Connection connection; | ||
|
|
||
| public StatementPersonDao(Connection connection) { | ||
| this.connection = connection; | ||
| } | ||
|
|
||
| public Optional<PersonEntity> getById(int id) throws SQLException { | ||
| String query = "SELECT id, name, FROM persons WHERE id = '" + id + "'"; | ||
|
|
||
| Statement statement = connection.createStatement(); | ||
| ResultSet resultSet = statement.executeQuery(query); | ||
|
|
||
| if (resultSet.first()) { | ||
| PersonEntity result = new PersonEntity(resultSet.getInt("id"), | ||
| resultSet.getString("name")); | ||
| return Optional.of(result); | ||
| } else { | ||
| return Optional.empty(); | ||
| } | ||
| } | ||
|
|
||
| public void insert(PersonEntity personEntity) throws SQLException { | ||
| String query = "INSERT INTO persons(id, name) VALUES(" + personEntity.getId() + ", '" | ||
| + personEntity.getName() + "')"; | ||
|
|
||
| Statement statement = connection.createStatement(); | ||
| statement.executeUpdate(query); | ||
| } | ||
|
|
||
| public void insert(List<PersonEntity> personEntities) throws SQLException { | ||
| for (PersonEntity personEntity : personEntities) { | ||
| insert(personEntity); | ||
| } | ||
| } | ||
|
|
||
| public void update(PersonEntity personEntity) throws SQLException { | ||
|
|
||
| String query = "UPDATE persons SET name = '" + personEntity.getName() + "' WHERE id = " | ||
| + personEntity.getId(); | ||
|
|
||
| Statement statement = connection.createStatement(); | ||
| statement.executeUpdate(query); | ||
|
|
||
| } | ||
|
|
||
| public void deleteById(int id) throws SQLException { | ||
| String query = "DELETE FROM persons WHERE id = " + id; | ||
| Statement statement = connection.createStatement(); | ||
| statement.executeUpdate(query); | ||
| } | ||
|
|
||
| public List<PersonEntity> getAll() throws SQLException { | ||
| String query = "SELECT id, name, FROM persons"; | ||
|
|
||
| Statement statement = connection.createStatement(); | ||
| ResultSet resultSet = statement.executeQuery(query); | ||
| List<PersonEntity> result = new ArrayList<>(); | ||
| while (resultSet.next()) { | ||
| result.add(new PersonEntity(resultSet.getInt("id"), resultSet.getString("name"))); | ||
| } | ||
| return result; | ||
| } | ||
| } |
22 changes: 22 additions & 0 deletions
22
...ence/src/test/java/com/baeldung/statmentVsPreparedstatment/DatasourceFactoryUnitTest.java
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,22 @@ | ||
| package com.baeldung.statmentVsPreparedstatment; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import java.sql.Connection; | ||
| import java.sql.SQLException; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertFalse; | ||
| import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
|
||
| class DatasourceFactoryUnitTest { | ||
|
|
||
| @Test | ||
| void whenCreateConnectionAndTables_thenConnectionIsOpenAndTableIsCreated() | ||
| throws SQLException, ClassNotFoundException { | ||
| DatasourceFactory factory = new DatasourceFactory(); | ||
| Connection connection = factory.getConnection(); | ||
|
|
||
| assertFalse(connection.isClosed()); | ||
| assertTrue(factory.createTables()); | ||
| } | ||
| } | ||
94 changes: 94 additions & 0 deletions
94
...test/java/com/baeldung/statmentVsPreparedstatment/PreparedStatementPersonDaoUnitTest.java
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,94 @@ | ||
| package com.baeldung.statmentVsPreparedstatment; | ||
|
|
||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import java.sql.Connection; | ||
| import java.sql.SQLException; | ||
| import java.util.Arrays; | ||
| import java.util.List; | ||
| import java.util.Optional; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.*; | ||
|
|
||
| class PreparedStatementPersonDaoUnitTest { | ||
| private PreparedStatementPersonDao dao; | ||
|
|
||
| @BeforeEach | ||
| void setup() throws SQLException, ClassNotFoundException { | ||
| DatasourceFactory datasourceFactory = new DatasourceFactory(); | ||
| Connection connection = datasourceFactory.getConnection(); | ||
| datasourceFactory.createTables(); | ||
| dao = new PreparedStatementPersonDao(connection); | ||
| } | ||
|
|
||
| @Test | ||
| void whenInsertAPerson_thenItNeverThrowsAnException() { | ||
| assertDoesNotThrow(() -> dao.insert(new PersonEntity(1, "john"))); | ||
| } | ||
|
|
||
| @Test | ||
| void whenInsertAPersonWithQuoteInText_thenItNeverThrowsAnException() { | ||
| assertDoesNotThrow(() -> dao.insert(new PersonEntity(1, "O'Brien"))); | ||
| } | ||
|
|
||
| @Test | ||
| void whenGetAPersonById_thenItReturnThePersonInDatabase() throws SQLException { | ||
| dao.insert(new PersonEntity(1, "john")); | ||
|
|
||
| Optional<PersonEntity> maybeEmployee = dao.getById(1); | ||
| assertTrue(maybeEmployee.isPresent()); | ||
|
|
||
| PersonEntity personEntity = maybeEmployee.get(); | ||
|
|
||
| assertEquals(1, personEntity.getId()); | ||
| assertEquals("john", personEntity.getName()); | ||
| } | ||
|
|
||
| @Test | ||
| void whenInsertAndGetMultiplePersons_thenItNeverThrowsAnException() throws SQLException { | ||
| assertDoesNotThrow(() -> dao.insert( | ||
| Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skit")))); | ||
|
|
||
| List<PersonEntity> result = dao.getAll(); | ||
|
|
||
| assertEquals(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skit")), | ||
| result); | ||
| } | ||
|
|
||
| @Test | ||
| void whenUpdateAnExistentPerson_thenItReturnsTheUpdatedPerson() throws SQLException { | ||
| dao.insert(new PersonEntity(1, "john")); | ||
| dao.update(new PersonEntity(1, "johnny")); | ||
|
|
||
| Optional<PersonEntity> maybePerson = dao.getById(1); | ||
|
|
||
| assertTrue(maybePerson.isPresent()); | ||
|
|
||
| PersonEntity personEntity = maybePerson.get(); | ||
|
|
||
| assertEquals(1, personEntity.getId()); | ||
| assertEquals("johnny", personEntity.getName()); | ||
| } | ||
|
|
||
| @Test | ||
| void whenDeleteAPersonById_thenItWillBeAbsentInDatabase() throws SQLException { | ||
| dao.insert(new PersonEntity(1, "john")); | ||
| dao.deleteById(1); | ||
|
|
||
| Optional<PersonEntity> maybePerson = dao.getById(1); | ||
|
|
||
alibenmessaoud marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| assertFalse(maybePerson.isPresent()); | ||
| } | ||
|
|
||
| @Test | ||
| void whenAHackerUpdateAPerson_thenItUpdatesTheTargetPerson() throws SQLException { | ||
| dao.insert(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skeet"))); | ||
| dao.update(new PersonEntity(1, "hacker' --")); | ||
|
|
||
| List<PersonEntity> result = dao.getAll(); | ||
|
|
||
| assertEquals(Arrays.asList(new PersonEntity(1, "hacker' --"), new PersonEntity(2, "skeet")), | ||
alibenmessaoud marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| result); | ||
| } | ||
| } | ||
Oops, something went wrong.
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.