feat: prepare statement

This commit is contained in:
Sergey Krylov 2026-03-03 05:33:28 +03:00
parent ba4dbe61db
commit c59f4fbed1

View File

@ -30,12 +30,15 @@ public class ProfileDao {
} }
public Profile save(Profile profile) { public Profile save(Profile profile) {
String sql = "INSERT INTO profile(email, password) VALUES (?, ?)";
try ( try (
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement(); PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
) { ) {
String sql = "INSERT INTO profile(email, password) VALUES ('%s', '%s')".formatted(profile.getEmail(), profile.getPassword());
int insertCount = statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS); statement.setString(1, profile.getEmail());
statement.setString(2, profile.getPassword());
int insertCount = statement.executeUpdate();
ResultSet res = statement.getGeneratedKeys(); ResultSet res = statement.getGeneratedKeys();
if (res.next()) { if (res.next()) {
@ -54,7 +57,7 @@ public class ProfileDao {
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
) { ) {
String sql = "SELECT * FROM profile WHERE id = %s".formatted(id); String sql = "SELECT * FROM profile WHERE id = '%s'".formatted(id);
ResultSet res = statement.executeQuery(sql); ResultSet res = statement.executeQuery(sql);
Profile profile = null; Profile profile = null;
@ -192,12 +195,14 @@ public class ProfileDao {
} }
public Optional<Profile> findByEmail(String email) { public Optional<Profile> findByEmail(String email) {
String sql = "SELECT * FROM profile WHERE email = ?";
try ( try (
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement statement = connection.createStatement(); PreparedStatement statement = connection.prepareStatement(sql);
) { ) {
String sql = "SELECT * FROM profile WHERE email = '%s'".formatted(email); statement.setString(1, email);
ResultSet res = statement.executeQuery(sql); ResultSet res = statement.executeQuery();
Profile profile = null; Profile profile = null;
if (res.next()) { if (res.next()) {