user(用户登录表) 字段名 类型 注释 其他 Username Varchar(50) 用户名 主键,非空 password varchar(50) 密码 空 根据以上内容使用Java写出增删改查的方法类
时间: 2023-06-16 14:06:47 浏览: 71
假设使用JDBC连接数据库,可以按照以下方式编写增删改查的方法类:
```java
import java.sql.*;
public class UserDao {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
public UserDao() {
try {
// 连接数据库
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
} catch (Exception e) {
e.printStackTrace();
}
}
// 增加用户
public boolean addUser(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());
int result = pstmt.executeUpdate();
if (result > 0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
// 删除用户
public boolean deleteUser(String username) {
try {
String sql = "DELETE FROM user WHERE username=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
int result = pstmt.executeUpdate();
if (result > 0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
// 修改用户密码
public boolean updateUser(User user) {
try {
String sql = "UPDATE user SET password=? WHERE username=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getPassword());
pstmt.setString(2, user.getUsername());
int result = pstmt.executeUpdate();
if (result > 0) {
return true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
// 查询用户
public User getUser(String username) {
try {
String sql = "SELECT * FROM user WHERE username=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, username);
rs = pstmt.executeQuery();
if (rs.next()) {
User user = new User();
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
return user;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void close() {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
其中,User是一个JavaBean类,包含username和password两个属性,以及对应的getters和setters方法。以上代码中使用了预编译SQL语句,可以有效避免SQL注入攻击。
阅读全文