You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java控制台无法显示SQL Server中book表数据的问题排查

问题分析与修复方案

你的代码能成功建立数据库连接并输出驱动相关信息,但无法展示书籍数据,核心问题出在这几个地方:

  • SQL语法错误:查询语句写成了"Select* from book",Select和*之间缺少空格,数据库无法正确解析这条SQL,导致查询执行失败。
  • 未处理连接为空的边界情况:如果第一个try块中连接获取失败,connection会是null,后续调用connection.prepareStatement()会直接抛出空指针异常。
  • 数据库资源未正确释放:PreparedStatement和ResultSet使用后没有关闭,会造成数据库连接资源泄漏。
  • 版本信息输出错误:你之前代码里的Product Version调用了getDatabaseProductName(),应该改成getDatabaseProductVersion()才能正确输出数据库版本。

修复后的完整代码

import java.sql.*;

public class Act1 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        
        try {
            String dbUrl = "jdbc:sqlserver://localhost:1433;databaseName=libreria;user=user1;password=pass";
            connection = DriverManager.getConnection(dbUrl);
            
            if (connection != null) {
                DatabaseMetaData dn = connection.getMetaData();
                System.out.println("Driver name: " + dn.getDriverName());
                System.out.println("Driver Version: " + dn.getDriverVersion());
                System.out.println("Product name: " + dn.getDatabaseProductName());
                System.out.println("Product Version: " + dn.getDatabaseProductVersion());
            }
            
            // 确保连接有效时再执行查询
            if (connection != null) {
                // 修复SQL语句的空格问题
                pst = connection.prepareStatement("SELECT * FROM book");
                rs = pst.executeQuery();
                
                while (rs.next()) {
                    // 注意:如果isbn是字符串类型(比如VARCHAR),请替换为rs.getString("isbn")
                    System.out.println("Isbn: " + rs.getInt("isbn") + " Title: " + rs.getString("title"));
                }
            }
            
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            // 按逆序关闭资源,避免泄漏
            try {
                if (rs != null) rs.close();
                if (pst != null) pst.close();
                if (connection != null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

额外提醒

如果你的book表中isbn字段是字符串类型(比如VARCHAR格式的ISBN码),一定要把rs.getInt("isbn")改成rs.getString("isbn"),否则会抛出类型不匹配的SQL异常,需要根据实际表结构调整字段的读取方式。

内容的提问来源于stack exchange,提问作者Samir Espeche

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 18:12:31