jdbc根据id查询信息
时间: 2023-07-07 08:11:42 浏览: 48
好的,您可以参考下面的Java代码来实现使用JDBC根据id查询信息:
```java
import java.sql.*;
public class JdbcDemo {
public static void main(String[] args) {
// JDBC连接信息
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
try {
// 1. 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 2. 创建Connection连接对象
Connection connection = DriverManager.getConnection(url, username, password);
// 3. 编写SQL语句
String sql = "SELECT * FROM user WHERE id = ?";
// 4. 创建PreparedStatement对象
PreparedStatement statement = connection.prepareStatement(sql);
// 5. 设置参数
int id = 1;
statement.setInt(1, id);
// 6. 执行查询操作
ResultSet resultSet = statement.executeQuery();
// 7. 处理查询结果
while (resultSet.next()) {
int userId = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println("id: " + userId + ", name: " + name + ", email: " + email);
}
// 8. 释放资源
resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们通过JDBC连接到MySQL数据库,然后执行了一个SQL查询语句,该语句根据id查询用户信息。其中,我们使用了PreparedStatement对象来设置查询参数以防止SQL注入攻击。最后,我们遍历ResultSet对象来处理查询结果,释放资源并关闭连接。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)