使用 Microsoft SQL Server JDBC Driver 时,所有数据库错误条件都作为异常通过 SQLServerException 类返回到 Java 应用程序。SQLServerException 类的下列方法继承自 java.sql.SQLException 和 java.lang.Throwable;并且可用于返回有关出现的 SQL Server 错误的特定信息。

在下面的实例中,将向此函数传递 SQL Server AdventureWorks 示例数据库的打开连接,并构造一条没有 FROM 子句、格式错误的 SQL 语句。然后运行该语句并处理 SQL 异常。

public static void executeSQLException(Connection con) {
   try {
      String SQL = "SELECT TOP 10 * Person.Contact";
      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(SQL);

      while (rs.next()) {
         System.out.println(rs.getString(4) + " " + rs.getString(6));
      }
      stmt.close();
   }
   catch (SQLException se) {
      do {
         System.out.println("SQL STATE: " + se.getSQLState());
         System.out.println("ERROR CODE: " + se.getErrorCode());
         System.out.println("MESSAGE: " + se.getMessage());
         System.out.println();
         se = se.getNextException();
      } while (se != null);
   }
}

请参阅

诊断与 JDBC 驱动程序有关的问题