0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SQLログの"?"を変換するツール

Posted at

SQLログの"?"を変換するツール

SQLログに出力される"?"を実際の値に置き換えるツール。

やりたいことのイメージ

アプリログなどに出力されるSQLログ

select a, b, c from table where aa = ? and bb = ? and cc = ?
Param:arg1,arg2,arg3

"?"を以下のように実際の値に置き換えるツール

select a, b, c from table where aa = arg1 and bb = arg2 and cc = arg3

前提(注意点)

今回のツールはコマンドプロンプトで実行するよう作成しています。

使い方

  1. 任意のディレクトリにファイルを格納

    • file(ディレクトリ)
      • args.txt
      • input.txt
    • IoTest.java
    • go.bat
      image.png
      image.png
  2. input.txt
    置換前の文言を記載
    例)select a, b, c from table where aa = ? and bb = ? and cc = ?

  3. args.txt
    置換文言を記載。
    ※カンマ区切り
    例)arg1,arg2,arg3

  4. 実行
    go.batを実行。
    実行すると
    "file/output.txt"が出力される

ファイル内容

go.bat

echo off
cd ./
javac IoTest.java
java IoTest
pause

IoTest.java

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

class IoTest {
	public static void main(String[] args) {
		FileReader inputFile = null;
		String[] argsFile;
		FileWriter outputFile = null;
		try {
			// 置き換え前ファイル読み込み
			inputFile = new FileReader(new File("./file/input.txt"));
			// 置き換え文字列ファイル読み込み
			argsFile = getArgsFile();
			// 置き換え後ファイル作成
			outputFile = new FileWriter(new File("./file/output.txt"));
			
			int argsIndex = 0;
			int ch = inputFile.read();
			while (ch != -1) {
				// 書き込み文字取得
				char wch = (char) ch;
				
				// 変換確認
				if (isConvertChar(wch)) {
					// 変換書き込み
					outputFile.write(argsFile[argsIndex]);
					argsIndex++;
				} else {
					// そのまま書き込み
					outputFile.write(wch);
				}

				ch = inputFile.read();
			}
			
			// 処理完了後はクローズ
			inputFile.close();
			outputFile.close();
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	private static String[] getArgsFile() throws Exception {
		String[] result;
		
		Path path = Paths.get("./file/args.txt");
		try {
			String str = Files.readString(path);
			result = convertArgsFile(str);
		} catch (Exception e) {
			System.out.println(e);
			throw e;
		}
		
		return result;
	}

	private static String[] convertArgsFile(String argsFile) throws Exception {
		String[] result = argsFile.split(",");
		return result;
	}

	private static boolean isConvertChar(char target) throws Exception {
		boolean result = false;

		if (target == '?') {
			return true;
		}

		return result;
	}
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?