EN
Java - how to make MySQL delete query with JDBC?
7 points
In Java it is possible to make SQL DELETE
query with JDBC in following way.
Note: read this article to know how to download and install JDBC driver proper way.
Note: this approach prevents of SQL Injection attack.
xxxxxxxxxx
1
package com.dirask.examples;
2
3
import java.sql.Connection;
4
import java.sql.DriverManager;
5
import java.sql.PreparedStatement;
6
import java.sql.SQLException;
7
8
public class Program {
9
10
private static final String DB_NAME = "test";
11
private static final String DB_HOST = "127.0.0.1"; // 'localhost'
12
private static final String DB_USER = "root";
13
private static final String DB_PASSWORD = "root";
14
15
private static final String DB_URL = "jdbc:mysql://" + DB_HOST + "/"
16
+ DB_NAME + "?serverTimezone=UTC";
17
18
public static void main(String[] args) throws ClassNotFoundException {
19
20
String sql = "DELETE FROM `users` WHERE `name` = ?";
21
22
try (
23
// gets connection with database
24
Connection connection = DriverManager.getConnection(DB_URL,
25
DB_USER, DB_PASSWORD);
26
27
// sends queries and receives results
28
PreparedStatement statement = connection.prepareStatement(sql);
29
) {
30
// this way to prevent sql injection
31
statement.setString(1, "John");
32
33
int count= statement.executeUpdate();
34
35
System.out.print("Number of deleted rows is " + count + ".");
36
} catch (SQLException e) {
37
// some logic depending on scenario
38
// maybe LOGGER.log(e.getMessage()) and "result false"
39
e.printStackTrace();
40
}
41
}
42
}
Output:
xxxxxxxxxx
1
Number of deleted rows is 1.
Database:

create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE `users` (
2
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
3
`name` VARCHAR(100) NOT NULL,
4
`role` VARCHAR(15) NOT NULL,
5
PRIMARY KEY (`id`)
6
)
7
ENGINE=InnoDB;
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO `users`
2
(`name`, `role`)
3
VALUES
4
('John', 'admin'),
5
('Chris', 'moderator'),
6
('Kate', 'user'),
7
('Denis', 'moderator');