Execute “sp_msforeachdb” in a Java application

后端 未结 3 1393
不知归路
不知归路 2020-12-03 20:25

Hi StackOverflow community :)

I come to you to share one of my problems...

I have to extract a list of every table in each database of a SQL Server i

3条回答
  •  离开以前
    2020-12-03 21:16

    UPDATE

    I've found the solution !

    After reading an article about sp_spaceused being used with Java, I figured out that I was in the same case.

    My final code is the following :

    this.instances = instances;
    for(int i = 0 ; i < this.instances.size() ; i++)
    {
        try
        {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            this.connect = DriverManager.getConnection("jdbc:sqlserver://" + this.instances.get(i), "tluser", "result");
    
            this.statement = this.connect.prepareCall("{call sp_msforeachdb(?)}");
            this.statement.setString(1, "Use ?; SELECT DB_NAME() AS DB, name FROM sys.tables WHERE DB_NAME() NOT IN('master', 'model', 'msdb', 'tempdb')");
            this.resultats = this.statement.execute();
    
            while(true)
            {
                int rowCount = this.statement.getUpdateCount();
                if(rowCount > 0)
                {
                    this.statement.getMoreResults();
                    continue;
                }
                if(rowCount == 0)
                {
                    this.statement.getMoreResults();
                    continue;
                }
    
                ResultSet rs = this.statement.getResultSet();
                if(rs != null)
                {
                    while (rs.next())
                    {
                         this.sortie.ecrireResultats(rs); // Write the results to a file
                    }
                    rs.close();
                    this.statement.getMoreResults();
                    continue;
                }
                break;
            }
            this.statement.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    

    It tried it out and my file has everything I want in it.

    Thank you all for your help ! :)

提交回复
热议问题