servlet执行sql脚本

package cn.test.web.manager;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InitServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String path = InitServlet.class.getClassLoader().getResource("init.sql").getPath();
		path = path.substring(1);
		System.out.println(path);
		String command = "cmd /c mysql -uroot -proot <" + path;
		
		//得到执行以上命令的进程
		Process p = Runtime.getRuntime().exec(command);
		
		//得到执行进程的错误消息
		InputStream in = p.getErrorStream();
		
		StringBuffer sb = new StringBuffer();
		byte buffer[] = new byte[1024];
		int len = 0;
		while ((len = in.read(buffer)) > 0) {
			sb.append(new String(buffer,0,len));
		}
		if(sb.length()>0){
			request.setAttribute("message", "系统初始化失败!原因:" + sb.toString());
		}else{
			request.setAttribute("message", "系统初始化成功!!");
		}
		request.getRequestDispatcher("/message.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

你可能感兴趣的:(Java,servlet,sql,buffer,string,command,path)