java用查询数据库表并显示
时间: 2024-02-28 22:04:51 浏览: 29
好的,这里提供一个简单的 Java 代码示例,可以连接到数据库,查询表中的数据并将其显示出来。在这个示例中,我们使用了 MySQL 数据库。
```java
import java.sql.*;
public class DatabaseExample {
public static void main(String[] args) {
try {
// 连接到 MySQL 数据库
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
// 创建 Statement 对象
Statement stmt = conn.createStatement();
// 执行查询语句
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// 遍历结果集并输出数据
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name") + " " + rs.getInt("age"));
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
```
在这个示例中,我们首先使用 `DriverManager.getConnection()` 方法连接到 MySQL 数据库。然后,我们创建一个 `Statement` 对象并使用 `executeQuery()` 方法执行一个查询语句。结果集通过 `next()` 方法遍历,并使用 `getInt()`、`getString()` 等方法获取数据。最后,我们关闭 ResultSet、Statement 和 Connection 对象以释放资源。
相关推荐
![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)