在Java中連接數據庫并實現增刪改查功能通常需要使用JDBC(Java Database Connectivity)技術。以下是一個簡單的示例演示如何連接數據庫并實現增刪改查功能:
1、導入必要的包:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
```
2、建立數據庫連接:
```java
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
```
3、實現查詢功能:
```java
String query = "SELECT * FROM mytable";
PreparedStatement statement = conn.prepareStatement(query);
ResultSet result = statement.executeQuery();
while (result.next()) {
// 處理結果集
}
```
4、實現插入功能:
```java
String insertQuery = "INSERT INTO mytable (column1, column2) VALUES (?, ?)";
PreparedStatement insertStatement = conn.prepareStatement(insertQuery);
insertStatement.setString(1, "value1");
insertStatement.setString(2, "value2");
insertStatement.executeUpdate();
```
5、實現更新功能:
```java
String updateQuery = "UPDATE mytable SET column1 = ? WHERE column2 = ?";
PreparedStatement updateStatement = conn.prepareStatement(updateQuery);
updateStatement.setString(1, "new value");
updateStatement.setString(2, "target value");
updateStatement.executeUpdate();
```
6、實現刪除功能:
```java
String deleteQuery = "DELETE FROM mytable WHERE column = ?";
PreparedStatement deleteStatement = conn.prepareStatement(deleteQuery);
deleteStatement.setString(1, "target value");
deleteStatement.executeUpdate();
```
以上是一個簡單的示例,實際情況中可能需要根據具體需求進行更復雜的操作。同時,為了保證代碼的健壯性和安全性,通常需要添加異常處理、連接管理等功能。