javaweb基于JDBC实现单表的CRUD数据库操作
时间: 2023-08-29 09:04:32 浏览: 118
好的,我可以为您解答这个问题。
首先,需要导入JDBC相关的jar包,然后建立数据库连接。以下是一个基本的数据库连接的示例代码:
```java
// 导入JDBC相关的jar包
import java.sql.*;
public class DBUtil {
// 数据库连接信息
private static final String URL = "jdbc:mysql://localhost:3306/db_name?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
private static final String USER = "root";
private static final String PASSWORD = "123456";
// 获取数据库连接
public static Connection getConnection() {
Connection conn = null;
try {
// 注册JDBC驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 建立数据库连接
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
```
接下来,我们可以使用JDBC实现单表的CRUD操作。以下是一个基本的示例代码:
```java
// 导入JDBC相关的jar包
import java.sql.*;
public class UserDaoImpl implements UserDao {
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
// 构造函数中获取数据库连接
public UserDaoImpl() {
conn = DBUtil.getConnection();
}
// 关闭数据库连接
public void close() {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 增加数据
public void add(User user) {
try {
String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
}
// 删除数据
public void delete(int id) {
try {
String sql = "DELETE FROM user WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
}
// 修改数据
public void update(User user) {
try {
String sql = "UPDATE user SET username = ?, password = ? WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUsername());
pstmt.setString(2, user.getPassword());
pstmt.setInt(3, user.getId());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
}
// 查询数据
public User query(int id) {
User user = null;
try {
String sql = "SELECT * FROM user WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
return user;
}
}
```
以上是一个基于JDBC实现单表的CRUD操作的示例代码,您可以根据自己的实际需求进行修改和完善。
阅读全文