Java调用Mysql——格式及运行机制

阅读更多
命令格式:
command = "cmd /c mysql -h127.0.0.1 -utiger -p111111 test < d:\tpl.sql -f --default-character-set=utf8 


运行方式:
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(command);


信息处理:
// 收集所有错误信息
StreamRedirectGobbler errorGobbler = new StreamRedirectGobbler(proc
					.getErrorStream(), "ERROR", dbname);

// 收集所有输入信息
StreamRedirectGobbler outputGobbler = new StreamRedirectGobbler(
					proc.getInputStream(), "OUTPUT", "D:tmp.sql", dbname);
// 启动
errorGobbler.start();
outputGobbler.start();
// 返回子进程的出口值 0表示正常终止
exitVal = proc.waitFor();


信息处理类:
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class StreamRedirectGobbler extends Thread {

	private InputStream is;
	private String type;
	private String fileName;
	private String dbname;

	public void setDbname(String dbname) {
		this.dbname = dbname;
	}

	StreamRedirectGobbler(InputStream is, String type, String fileName,
			String dbname) {
		this.is = is;
		this.type = type;
		this.fileName = fileName;
		this.dbname = dbname;
	}

	StreamRedirectGobbler(InputStream is, String type, String dbname) {
		this(is, type, null, dbname);
	}

	public void run() {
		PrintWriter pw = null;
		try {
			if (fileName != null) {
				pw = new PrintWriter(new FileOutputStream(fileName));
			}

			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String line = null;

			// 获取输入 并把 输入作为输出 进行重定向
			while ((line = br.readLine()) != null) {
				//System.out.println(dbname);
				line = line.replace("[dbname]", dbname);
				//System.out.println(pw);
				if (pw != null)
					pw.println(line);
				System.out.println(type + ">" + line);
			}
			if (pw != null)
				pw.flush();

		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			if (pw != null)
				pw.close();
		}
	}

}

你可能感兴趣的:(Java,MySQL,SQL,thread,C)