下面是一個簡單的示例代碼,演示如何使用JDBC進行增刪改查操作:
1、增加數據:
```java
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "INSERT INTO table_name (column1, column2) VALUES (?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "value1");
stmt.setString(2, "value2");
stmt.executeUpdate();
conn.close();
```
2、刪除數據:
```java
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "DELETE FROM table_name WHERE column1 = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "value1");
stmt.executeUpdate();
conn.close();
```
3、更新數據:
```java
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "UPDATE table_name SET column1 = ? WHERE column2 = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "new_value");
stmt.setString(2, "value2");
stmt.executeUpdate();
conn.close();
```
4、查詢數據:
```java
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT * FROM table_name WHERE column1 = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, "value1");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("column1"));
System.out.println(rs.getString("column2"));
}
conn.close();
```
請注意,以上示例代碼是基于JDBC API,需要導入相應的包,并且需要替換相應的url、username、password、table_name、column和value等信息。