在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()
等方法获取查询结果的具体字段值,并将其显示出来。记得在代码中添加合适的异常处理,同时在最后关闭数据库连接和结果集对象,以释放资源。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: mysql怎么显示所有数据库