tags:

views:

245

answers:

1

I'm trying to write a program in Java that uses osql to generate a list of databases on a server. My code is as follows:

    public Object[] findDataBases(String server, String user, String passwd){
    str = new String[] {"cmd.exe", "/c", "osql", " -S ", 
            server, " -U", user, "&&", "-P ", passwd, 
                            "&&", "sp_databases","&&", "GO"     
            };
    Runtime rt = Runtime.getRuntime();
    try{

        Process p = rt.exec(str);
        InputStream is = p.getInputStream();
        InputStream err = p.getErrorStream();
        InputStreamReader in = new InputStreamReader(is);
        InputStreamReader er = new InputStreamReader(err);

        BufferedReader buff = new BufferedReader(in);
        String line = buff.readLine();
        ArrayList<String> listDatabases = new ArrayList<String>();
        while (line != null){
            listDatabases.add(line.trim());
            /*for (int i = 0; i<4; i++){
                buff.readLine();
            }*/
            line =buff.readLine();
        }
        System.out.println("error stream:");
        buff = new BufferedReader(er);

        while ((line=buff.readLine()) != null){
            System.err.println(line);
        }

        databases = listDatabases.toArray();
        return databases;
    }

When I run this, for some reason I get a message as if I had run osql -?, which I obviously have not done.

I'm not sure what I'm doing wrong, so any help would be appreciated. Thanks so much!

+1  A: 

remove spaces from the arguments take && off: str = new String[] {"cmd.exe", "/c", "osql", "-S", server, "-U", user, "-P", passwd, "-Q", "sp_databases"};

Moisei
I just tried this, and I got the following error: [SQL Native Client]Named Pipes Provider: Could not open a connection to SQLServer [67].[SQL Native Client]Login timeout expired[SQL Native Client]An error has occurred while establishing a connection tothe server. When connecting to SQL Server 2005, this failure may be caused bythe fact that under the default settings SQL Server does not allow remoteconnections.
chama
which means the command line executed properly now but you have a problem with connection to your SQL server.It would be much helpful if you post here the full command line as you run it from the command prompt.Also try it first in the prompt and make sure it does the job.
Moisei
It does do it in the command prompt - I tried it. I think that after I used your code, the problem was with my server. Either I misspelled the name of the server in my variable, or there was an issue with the instance of it (\\ instead of / in a java string?). After I changed that, it worked. Thanks so much for your help.
chama