要使用Maven實現數據庫增刪改查功能,您需要在Maven項目中添加數據庫驅動依賴,然后編寫數據庫操作的代碼。以下是一個簡單的示例:
1、添加mysql數據庫驅動依賴到pom.xml文件中:
```xml
```
2、編寫數據庫操作的Java代碼:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseOperations {
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASSWORD = "password";
public void insertData(String name, String email) {
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, name);
stmt.setString(2, email);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateData(int id, String email) {
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
String sql = "UPDATE users SET email = ? WHERE id = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, email);
stmt.setInt(2, id);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteData(int id) {
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
String sql = "DELETE FROM users WHERE id = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, id);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void queryData() {
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
String sql = "SELECT * FROM users";
try (PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
DatabaseOperations db = new DatabaseOperations();
db.insertData("Alice", "alice@example.com");
db.updateData(1, "alice.new@example.com");
db.deleteData(1);
db.queryData();
}
}
```
這個示例代碼演示了如何使用Maven項目實現數據庫的增刪改查功能。您需要根據自己的數據庫連接信息修改URL、USER和PASSWORD參數,然后通過調用不同的方法實現相應的數據庫操作。在main方法中,我們創建了DatabaseOperations對象并調用了insertData、updateData、deleteData和queryData方法來執行相應的數據庫操作。