java根据id查询用户信息
时间: 2024-05-16 16:15:59 浏览: 8
假设你的用户信息存在于一个名为"users"的表中,表结构包含id, name, age等字段,可以使用以下代码实现根据id查询用户信息:
```java
import java.sql.*;
public class UserInfoDAO {
private final String url = "jdbc:mysql://localhost:3306/mydatabase";
private final String user = "root";
private final String password = "mypassword";
public UserInfo getUserById(int id) {
UserInfo user = null;
String query = "SELECT * FROM users WHERE id = ?";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setInt(1, id);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
user = new UserInfo();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return user;
}
}
```
在代码中,我们首先定义了连接数据库需要的url、user和password,然后定义一个getUserById方法,该方法接受一个int类型的id作为参数,并返回一个UserInfo类型的对象。在方法中,我们首先定义了一个UserInfo对象,然后使用PreparedStatement创建了一个带有参数的查询语句,将id作为参数设置到查询语句中,并通过executeQuery方法执行查询。如果查询到了结果,就将结果封装到UserInfo对象中,并返回该对象。如果查询出错,就打印出错信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)