Java在Linux環境下執行MySQL命令沒法獲取結果的問題

背景

最近項目中包含一些導出功能,一些功能須要多表查詢才能夠知足需求,也有一些數據僅是單表查詢。在此以前想到過兩種方案,第一種是查詢出數據後經過EasyExcle寫入文件,另外一種是使用MySQL自帶的導出功能。但在嘗試第二種方案時遇到一些問題,記錄以下。java

問題

在執行單表導出的過程當中,我使用了MySQL自帶的命令完成。即在代碼中經過字符串拼接命令。例如:
imagemysql

即使是這條語句經過Java程序調用仍是會執行失敗。失敗的緣由有兩個:linux

  1. 經過Java代碼調用命令會出現程序卡死,致使後面的程序沒法執行,須要手動處理
  2. 須要告訴操做系統這並不是字符串而是命令

解決

import java.io.*;

/**
 * @description:
 * @author: 582895699@qq.com
 * @time: 2020/11/26 下午 11:17
 */
public class Test {
    public static void main(String[] args) {
        executeCommand();
    }

    public static void executeCommand() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("mysql -uroot -proot -D test -e 'select * from goods where id=1'");
        stringBuilder.append(" > ");
        stringBuilder.append("/tmp/20201128.csv");
        // 告訴操做系統並不是字符串,而是命令
        String[] command = {"/bin/bash", "-c", stringBuilder.toString()};
        try {
            Process process = Runtime.getRuntime().exec(command);
            printMessage(process.getInputStream());
            printMessage(process.getErrorStream());
            // 等待命令執行完畢
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 另起一個線程輸出錯誤流
     *
     * @param input
     */
    private static void printMessage(final InputStream input) {
        new Thread(() -> {
            Reader reader = new InputStreamReader(input);
            BufferedReader bf = new BufferedReader(reader);
            String line = null;
            try {
                while ((line = bf.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

若有問題,歡迎指正
原文連接:Java在Linux環境下執行MySQL命令沒法獲取結果的問題 | 海子 | Keep Moving (haicheng.website)web

相關文章
相關標籤/搜索