sql查询出hostname以及对应的所有ip,现在我需要返回一个hostname以及它对应的所有ip地址,怎么写 java
时间: 2024-05-03 09:22:25 浏览: 17
下面是一个用Java编写的示例代码,用于从数据库中查询主机名及其对应的所有IP地址:
```
import java.sql.*;
public class HostnameIPQuery {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 设置数据库连接参数
String url = "jdbc:mysql://localhost/mydatabase";
String user = "root";
String password = "mypassword";
// 创建数据库连接
conn = DriverManager.getConnection(url, user, password);
// 创建查询语句
String sql = "SELECT hostname, ip FROM hosts";
stmt = conn.createStatement();
// 执行查询
rs = stmt.executeQuery(sql);
// 遍历结果集并打印
while (rs.next()) {
String hostname = rs.getString("hostname");
String ip = rs.getString("ip");
System.out.println(hostname + ": " + ip);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
```
该代码将查询数据库中名为“hosts”的表,并返回每个主机名及其对应的所有IP地址。在具体应用中,您可以根据需要修改查询语句和数据库连接参数。