共计 1709 个字符,预计需要花费 5 分钟才能阅读完成。
在 Java 中,可以使用 JDBC(Java Database Connectivity)来连接数据库并执行查询操作。以下是一个简单的示例代码,用于查询数据库并显示结果:
import java.sql.*;
public class DatabaseQuery {????public?static?void?main(String[]?args)?{
????????//?JDBC 连接的数据库 URL、用户名和密码
????????String?url?=“jdbc:mysql://localhost:3306/mydatabase”;
????????String?username?=“root”;
????????String?password?=“password”;
????????//?定义数据库连接对象和结果集对象
????????Connection?conn?=?null;
????????Statement?stmt?=?null;
????????ResultSet?rs?=?null;
????????try?{
????????????//?连接数据库
????????????conn?=?DriverManager.getConnection(url,?username,?password);
????????????//?创建 Statement 对象
????????????stmt?=?conn.createStatement();
????????????//?定义查询语句
????????????String?sql?=“SELECT?*?FROM?mytable”;
????????????//?执行查询并获取结果集
????????????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);
????????????}
????????}?catch?(SQLException?e)?{
????????????e.printStackTrace();
????????}?finally?{
????????????//?关闭数据库连接和结果集
????????????try?{
????????????????if?(rs?!=?null)?{
????????????????????rs.close();
????????????????}
????????????????if?(stmt?!=?null)?{
????????????????????stmt.close();
????????????????}
????????????????if?(conn?!=?null)?{
????????????????????conn.close();
????????????????}
????????????}?catch?(SQLException?e)?{
????????????????e.printStackTrace();
????????????}
????????}
????}
}
上述代码使用了 MySQL 数据库作为示例,可以根据实际情况修改数据库 URL、用户名和密码。将查询语句修改为需要执行的 SQL 查询语句,然后通过 rs.getInt()
、rs.getString()
等方法获取查询结果的具体字段值,并将其显示出来。记得在代码中添加合适的异常处理,同时在最后关闭数据库连接和结果集对象,以释放资源。
丸趣 TV 网 – 提供最优质的资源集合!