Search code examples
javasql-serverresultsetexecutequerydbcc

DBCC CHECKDB did not return a result set in Java ( MS SQL )


Here is my Function:

private static void checkDatabase(String dbName, String password) {
    try{
        Connection con=DriverManager.getConnection(
                "jdbc:sqlserver://localhost;database="+dbName+ ";user=SA;password=" +password);
        Statement stmt=con.createStatement();
        ResultSet rs=stmt.executeQuery("DBCC CHECKDB;");
        while(rs.next()){
          System.out.println( //TODO );
        }
            con.close();
    }catch(Exception e){ System.out.println(e);}
}
  1. I wanna use DBCC CHECKDB to check all Databases but got this Error:

     com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set. 
    

    Why DBCC CHECK DB can not work with executeQuery() and how can i fix it ?

  2. So if i have already ResultSet from stmt.executeQuery(), how can i read this Result as Lines or String? I want to read how many Errors are there. Thank you.


Solution

  • DBCC CHECKDB returns results as messages rather than a result set by default. Specify the TABLERESULTS option (DBCC CHECKDB WITH TABLERESULTS;) so results are returned as rows instead of messages.

    Alternatively, you could use the execute method instead of executeQuery and get the returned messages using getWarnings:

    stmt.execute("DBCC CHECKDB;");
    SQLWarning w = stmt.getWarnings();
    while(w != null) {
        System.out.println(w.getMessage());
        w = w.getNextWarning();
    }