加載 MySQL 驅動:
Class.forName("com.mysql.jdbc.Driver");
建立數據庫連接:
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "password");
創建 Statement 對象:
Statement stmt = conn.createStatement();
定義并執行 SQL 語句:
String sql = "insert into user(name, age) values ('user1', 18)";
int result = stmt.executeUpdate(sql);
創建 Statement 對象:
Statement stmt = conn.createStatement();
定義并執行 SQL 語句:
String sql = "delete from user where name = 'user1'";
int result = stmt.executeUpdate(sql);
創建 Statement 對象:
Statement stmt = conn.createStatement();
定義并執行 SQL 語句:
String sql = "update user set age = 20 where name = 'user1'";
int result = stmt.executeUpdate(sql);
創建 Statement 對象:
Statement stmt = conn.createStatement();
定義并執行 SQL 語句:
String sql = "select * from user";
ResultSet rs = stmt.executeQuery(sql);
處理查詢結果:
while (rs.next()) {
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
}