java实现数据库查询
时间: 2023-11-18 19:02:13 浏览: 40
要实现数据库查询,首先需要连接到数据库,然后执行 SQL 查询语句,最后获取查询结果。以下是使用 Java 连接 MySQL 数据库并执行查询的示例代码:
```java
import java.sql.*;
public class QueryExample {
public static void main(String[] args) {
try {
// 连接到 MySQL 数据库
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "mypassword";
Connection conn = DriverManager.getConnection(url, username, password);
// 执行 SQL 查询语句
String sql = "SELECT * FROM mytable WHERE age > 18";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,首先定义了连接 MySQL 数据库所需的 URL、用户名和密码,然后通过 `DriverManager.getConnection()` 方法连接到数据库。
然后使用 `conn.createStatement()` 方法创建一个 `Statement` 对象,再使用 `stmt.executeQuery()` 方法执行 SQL 查询语句,将查询结果存储在一个 `ResultSet` 对象中。
最后通过 `while` 循环遍历 `ResultSet` 对象中的每一行数据,使用 `rs.getInt()` 和 `rs.getString()` 方法获取每一列的值。
最后记得要关闭连接,释放资源。
相关推荐
![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_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)