Java:完成对用户表 的增删改查 用户表字段 ID username password
时间: 2023-10-26 11:06:09 浏览: 80
java实现用户的增删改查
4星 · 用户满意度95%
好的,我可以为您提供Java代码来完成对用户表的增删改查操作。需要注意的是,这里假设您已经有了一个数据库连接对象conn,以及一个User类,其中包含了ID、username和password字段的定义。
1. 增加用户
```java
public void addUser(User user) {
try {
String sql = "INSERT INTO user (username, password) VALUES (?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, user.getUsername());
statement.setString(2, user.getPassword());
statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
```
2. 删除用户
```java
public void deleteUser(int id) {
try {
String sql = "DELETE FROM user WHERE id=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, id);
statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
```
3. 修改用户
```java
public void updateUser(User user) {
try {
String sql = "UPDATE user SET username=?, password=? WHERE id=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, user.getUsername());
statement.setString(2, user.getPassword());
statement.setInt(3, user.getId());
statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
```
4. 查询用户
```java
public User getUserById(int id) {
User user = null;
try {
String sql = "SELECT * FROM user WHERE id=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getInt("id"));
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
}
resultSet.close();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
```
以上就是Java代码实现对用户表进行增删改查操作的示例,希望对您有所帮助。
阅读全文