安卓在UserDao写一个查询mysql的user表所有内容的方法,并将此方法用到user.class中显示这些内容的完整实例代码
时间: 2024-02-19 17:57:55 浏览: 35
得到当前数据库中所有用户表信息
以下是在UserDao中查询mysql的user表所有内容的方法的样例代码:
```java
public List<User> getAllUsers() {
List<User> users = new ArrayList<>();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DbUtil.getConnection();
stmt = conn.createStatement();
String sql = "SELECT * FROM user";
rs = stmt.executeQuery(sql);
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
user.setPhone(rs.getString("phone"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DbUtil.close(conn, stmt, rs);
}
return users;
}
```
在这个方法中,我们使用了JDBC连接数据库,执行SQL查询语句,将查询结果封装成User对象,并将User对象保存在List中返回。在User类中,我们可以定义一个toString()方法来显示User对象的内容,例如:
```java
public class User {
private int id;
private String username;
private String password;
private String email;
private String phone;
// 省略getter和setter方法
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
```
然后我们可以在调用getAllUsers()方法后,遍历返回的List<User>,并调用每个User对象的toString()方法来显示其内容,例如:
```java
UserDao userDao = new UserDao();
List<User> users = userDao.getAllUsers();
for (User user : users) {
System.out.println(user.toString());
}
```
阅读全文