简体   繁体   中英

Not able to export csv file from mysql in java

I have a requirement to export mysql table data to be downloaded by user in CSV format.

To achieve this I am trying java runtime exec function and executing "mysql -e". Unfortunately, I am stuck half way. I am only able to display sql output to console but not able to route it to a file.

WORKING CODE

(I am able to see records in eclipse console)

try {
        Process p = Runtime.getRuntime().exec(new String[]
                {


                "mysql","-h","localhost","-u","admin","-pxyz","myDB","-e", "\"select concat(billing_amount,',') as 'Billing Amount,', concat(amount_paid ,',') as 'Amount Paid,' from invoice\""

                }
                );
         BufferedReader in = new BufferedReader(
                 new InputStreamReader(p.getInputStream()));
         String line = null;
         while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        //process.waitFor();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

But when I am trying to export data to a file using "> abc.txt " , the file is not created, instead I see the mySQL --help option in eclipse console. What could be wrong here?

CODE NOT WORKING

try {
        Process p = Runtime.getRuntime().exec(new String[]
                {


                "mysql","-h","localhost","-u","admin","-pxyz","myDB","-e", "\"select concat(billing_amount,',') as 'Billing Amount,', concat(amount_paid ,',') as 'Amount Paid,' from invoice\"", "> abc.txt"

                }
                );
         BufferedReader in = new BufferedReader(
                 new InputStreamReader(p.getInputStream()));
         String line = null;
         while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        //process.waitFor();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I/O redirection is handled by the shell, not by each program. Hence, mysql does not know how to handle > abc.txt . Executing a shell and passing the full command as a single argument like this would work in an Unix system:

Process p = Runtime.getRuntime().exec(new String[] {
     "sh", "-c", "mysql -h localhost -u admin -pxyz myDB -e \"select concat(billing_amount,',') as 'Billing Amount,', concat(amount_paid ,',') as 'Amount Paid,' from invoice\" > abc.txt"
});

But the better option, that does not assume an Unix shell, is to use a ProcessBuilder and the redirectOutput(File) method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM