Mã Java mẫu
Sử dụng Statement.executeUpdate() để chạy câu lệnh INSERT.
1. Tạo bảng MySQL
mysql> create table DemoTable(
Id int,
Name varchar(30),
CountryName varchar(30),
Age int
);
Query OK, 0 rows affected (0.66 sec)
2. Mã Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class AccessMySQLDatabase {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/web?useSSL=false", "root", "123456");
st = con.createStatement();
String sql = "insert into DemoTable(Id,Name,CountryName,Age) values(100,'David','AUS',24)";
int result = st.executeUpdate(sql);
if (result > 0) {
System.out.println("Record Inserted! Check your table now!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. Kết quả chạy
Record Inserted! Check your table now!
4. Kiểm tra bảng MySQL
mysql> select * from DemoTable;
+------+-------+-------------+------+ | Id | Name | CountryName | Age | +------+-------+-------------+------+ | 100 | David | AUS | 24 | +------+-------+-------------+------+ 1 row in set (0.00 sec)
Khuyến nghị: Dùng PreparedStatement thay vì Statement để tránh SQL Injection và xử lý kiểu dữ liệu tốt hơn.