Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Cách cập nhật dữ liệu trong MySQL bằng Java (JDBC)

Sử dụng lệnh UPDATE trong Java JDBC để sửa dữ liệu.

Cú pháp SQL:

UPDATE tên_bảng SET cột1=giá_trị1,... WHERE điều_kiện;

Ví dụ Java hoàn chỉnh:

import java.sql.*;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class JavaUpdateDemo {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = (Connection) DriverManager.getConnection(
                "jdbc:mysql://localhost/business", "Manish", "123456");
            System.out.println("Kết nối thành công");
            stmt = (Statement) conn.createStatement();
            String sql = "UPDATE UpdateDemo SET Name='Johnson' WHERE id IN(1,4)";
            stmt.executeUpdate(sql);
            System.out.println("Cập nhật thành công");
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try { if (stmt != null) stmt.close(); } catch (SQLException ignored) {}
            try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
        }
    }
}

Kết quả: các hàng id 1 và 4 được cập nhật Name thành 'Johnson'.