在Java中连接数据库并实现增删改查功能通常需要使用JDBC(Java Database Connectivity)技术。以下是一个简单的示例演示如何连接数据库并实现增删改查功能:
1、导入必要的包:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
2、建立数据库连接:
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
3、实现查询功能:
String query = "SELECT * FROM mytable";
PreparedStatement statement = conn.prepareStatement(query);
ResultSet result = statement.executeQuery();
while (result.next()) {
// 处理结果集
}
4、实现插入功能:
String insertQuery = "INSERT INTO mytable (column1, column2) VALUES (?, ?)";
PreparedStatement insertStatement = conn.prepareStatement(insertQuery);
insertStatement.setString(1, "value1");
insertStatement.setString(2, "value2");
insertStatement.executeUpdate();
5、实现更新功能:
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、实现删除功能:
String deleteQuery = "DELETE FROM mytable WHERE column = ?";
PreparedStatement deleteStatement = conn.prepareStatement(deleteQuery);
deleteStatement.setString(1, "target value");
deleteStatement.executeUpdate();
以上是一个简单的示例,实际情况中可能需要根据具体需求进行更复杂的操作。同时,为了保证代码的健壮性和安全性,通常需要添加异常处理、连接管理等功能。