java面试项目中遇到的难点,03-增删改查实现
在Java中实现增删改查(CRUD)通常涉及到数据库操作。以下是一个简单的例子,使用JDBC来实现对数据库表的CRUD操作。
首先,确保你有一个数据库表,例如:
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
然后,使用JDBC实现CRUD操作:
import java.sql.*;
public class UserDao {
private Connection connect = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public UserDao() {
try {
// 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立数据库连接
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "username", "password");
} catch (Exception e) {
e.printStackTrace();
}
}
// 增加用户
public boolean insert(User user) {
try {
String query = "INSERT INTO users (name, email) VALUES (?, ?)";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getEmail());
return preparedStatement.executeUpdate() > 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// 删除用户
public boolean delete(int id) {
try {
String query = "DELETE FROM users WHERE id = ?";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setInt(1, id);
return preparedStatement.executeUpdate() > 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// 修改用户
public boolean update(User user) {
try {
String query = "UPDATE users SET name = ?, email = ? WHERE id = ?";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getEmail());
preparedStatement.setInt(3, user.getId());
return preparedStatement.executeUpdate() > 0;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// 查询用户
public User search(int id) {
try {
String query = "SELECT * FROM users WHERE id = ?";
preparedStatement = connect.prepareStatement(query);
preparedStatement.setInt(1
评论已关闭