EN
Java - how to make MySQL update query with JDBC?
1 points
In Java it is possible to make SQL UPDATE
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 = "UPDATE `users` SET `name` = ?, `role` = ? WHERE `id` = ?";
21
22
try (
23
// gets connection with database
24
Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
25
26
// sends queries and receives results
27
PreparedStatement statement = connection.prepareStatement(sql);
28
) {
29
// this way to prevent sql injection
30
statement.setString(1, "Matt");
31
statement.setString(2, "admin");
32
statement.setInt(3, 3);
33
34
int count= statement.executeUpdate();
35
36
System.out.print("Number of updated rows is " + count + ".");
37
} catch (SQLException e) {
38
// some logic depending on scenario
39
// maybe LOGGER.log(e.getMessage()) and "result false"
40
e.printStackTrace();
41
}
42
}
43
}
Output:
xxxxxxxxxx
1
Number of updated 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');