Java数据库查询的内容输出
时间: 2023-11-22 22:56:10 浏览: 117
Java数据库查询的内容输出需要通过JDBC连接到数据库,执行SQL语句并将结果输出到控制台或者其他输出流。以下是一个简单的Java数据库查询示例:
```java
import java.sql.*;
public class DatabaseQueryExample {
public static void main(String[] args) {
try {
// 创建数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 创建SQL语句并执行
String sql = "SELECT * FROM student WHERE age > 18";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
// 输出查询结果
while (rs.next()) {
System.out.println(rs.getInt("id") + "\t" + rs.getString("name") + "\t" + rs.getInt("age"));
}
// 关闭查询结果、SQL语句、数据库连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
上述代码中,使用JDBC连接到MySQL数据库,查询student表中年龄大于18岁的数据,并将查询结果输出到控制台。其中,getConnection方法的第一个参数为数据库连接地址,第二个参数为数据库用户名,第三个参数为数据库密码。执行SQL语句需要创建Statement对象,并调用其executeQuery方法,返回一个ResultSet结果集对象。通过while循环遍历结果集,使用getInt、getString等方法获取每条记录的字段值。最后,需要关闭ResultSet、Statement和Connection对象,释放资源。
阅读全文
相关推荐
















