java前端显示数据库查询结果
时间: 2024-03-06 22:46:50 浏览: 19
要在Java前端显示数据库查询结果,你需要使用Java数据库连接(JDBC)API来连接数据库并执行查询。以下是一个基本的示例代码:
```java
import java.sql.*;
public class DisplayData {
public static void main(String[] args) {
try {
// Connect to the database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
// Prepare the SQL statement
String sql = "SELECT * FROM mytable";
Statement stmt = conn.createStatement();
// Execute the query and get the result set
ResultSet rs = stmt.executeQuery(sql);
// Loop through the result set and display the data
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);
}
// Close the connection and release resources
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
在这个示例中,我们连接到名为“mydb”的MySQL数据库,执行一个简单的SELECT语句,并从结果集中提取ID、姓名和年龄字段。你可以根据自己的需求更改查询和结果集的处理方式。