jdbc实现DAO模型
时间: 2025-01-05 17:45:58 浏览: 4
JDBC(Java Database Connectivity)是一种用于执行SQL语句的Java API,它提供了一种标准的方法来连接和操作关系型数据库。DAO(Data Access Object)模型是一种设计模式,用于将数据访问逻辑与业务逻辑分离。通过JDBC实现DAO模型,可以使代码更加模块化、可维护和可扩展。
以下是一个简单的示例,展示如何使用JDBC实现DAO模型:
1. **创建数据库表**
首先,创建一个简单的数据库表,例如`users`表:
```sql
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
email VARCHAR(50)
);
```
2. **创建DAO接口**
定义一个DAO接口,声明数据访问方法:
```java
public interface UserDAO {
void addUser(User user);
User getUserById(int id);
List<User> getAllUsers();
void updateUser(User user);
void deleteUser(int id);
}
```
3. **创建实体类**
创建一个`User`实体类,表示数据库中的用户:
```java
public class User {
private int id;
private String name;
private String email;
// Getters and Setters
}
```
4. **实现DAO接口**
创建一个`UserDAOImpl`类,实现`UserDAO`接口,并使用JDBC进行数据库操作:
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class UserDAOImpl implements UserDAO {
private Connection connection;
public UserDAOImpl() {
try {
// 加载数据库驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立数据库连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
@Override
public void addUser(User user) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, user.getName());
statement.setString(2, user.getEmail());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public User getUserById(int id) {
String sql = "SELECT * FROM users WHERE id = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
return user;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public List<User> getAllUsers() {
List<User> users = new ArrayList<>();
String sql = "SELECT * FROM users";
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
@Override
public void updateUser(User user) {
String sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, user.getName());
statement.setString(2, user.getEmail());
statement.setInt(3, user.getId());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void deleteUser(int id) {
String sql = "DELETE FROM users WHERE id = ?";
try (PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setInt(1, id);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close() {
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
5. **使用DAO**
在业务逻辑中使用`UserDAO`进行数据操作:
```java
public class Main {
public static void main(String[] args) {
UserDAO userDAO = new UserDAOImpl();
User user = new User();
user.setName("John Doe");
user.setEmail("john.doe@example.com");
// 添加用户
userDAO.addUser(user);
// 获取用户
User retrievedUser = userDAO.getUserById(1);
System.out.println("User: " + retrievedUser.getName() + ", " + retrievedUser.getEmail());
// 更新用户
retrievedUser.setEmail("john.new@example.com");
userDAO.updateUser(retrievedUser);
// 删除用户
userDAO.deleteUser(1);
// 获取所有用户
List<User> users = userDAO.getAllUsers();
for (User u : users) {
System.out.println("User: " + u.getName() + ", " + u.getEmail());
}
userDAO.close();
}
}
```
通过上述步骤,你可以使用JDBC实现一个简单的DAO模型,进行基本的CRUD(创建、读取、更新、删除)操作。
阅读全文