Guest User

Untitled

a guest
Jul 23rd, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.27 KB | None | 0 0
  1. public class MysqlUtil {
  2.  
  3. private static String USERNAME;//数据库用户名
  4. private static String PASSWORD;//数据库用户密码
  5. private static String PORT;//数据库开放端口
  6. private static String IP;//数据库ip地址
  7. private static String DATABASENAME;//数据库名称
  8.  
  9. private static Log LOG = LogFactory.getServiceLog(MysqlUtil.class);
  10.  
  11. /**
  12. * 配置数据库连接信息
  13. * @param username 数据库用户名
  14. * @param password 数据库用户密码
  15. * @param databaseName 数据库名称
  16. * @param ip 数据库ip地址
  17. * @param port 数据库开放端口
  18. */
  19. public static void config(String username,String password,String databaseName,String ip,String port){
  20. MysqlUtil.USERNAME = username;
  21. MysqlUtil.PASSWORD = password;
  22. MysqlUtil.DATABASENAME = databaseName;
  23. MysqlUtil.PORT = port;
  24. MysqlUtil.IP = ip;
  25. LOG.info(ClassUtil.getMethodName(), "MysqlUtil完成初始化!");
  26. }
  27.  
  28. /**
  29. * 根据数据库表名查找对应创建该表的sql语句脚本
  30. * @param tableName 数据库名
  31. * @return 创建该表的sql语句脚本
  32. * @throws IOException 文件读写错误
  33. */
  34. public static String getTableSql(String tableName) throws IOException{
  35. File f = getMysqlDump();
  36. if(f == null){
  37. throw new FileNotFoundException("在lib路径下没有找到名为'mysqldump'的mysql工具,MysqlDumpUtil类的功能依赖此文件!");
  38. }
  39.  
  40. //构建远程数据库命令字符串
  41. StringBuilder cmdStr = new StringBuilder();
  42. cmdStr.append(" -d --compact -u")
  43. .append(USERNAME)
  44. .append(" -p")
  45. .append(PASSWORD)
  46. .append(" -h")
  47. .append(IP)
  48. .append(" -P")
  49. .append(PORT)
  50. .append(" ").append(DATABASENAME)
  51. .append(" ").append(tableName);
  52.  
  53. Runtime rt = Runtime.getRuntime();
  54. //数据库构建表的sql脚本
  55. StringBuilder tableSql = new StringBuilder();
  56. // 调用mysqldump的cmd命令
  57. Process p = null;
  58. if(isWindows()){
  59. p = rt.exec(new String[]{"cmd","/c",f.getPath() + cmdStr.toString()});
  60. } else {
  61. p = rt.exec(new String[]{"sh","-c","cd "+ f.getParent() + " | mysqldump " + cmdStr.toString()});
  62. }
  63. // 把进程执行中的控制台输出信息写入.sql文件
  64. // 注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行
  65. InputStream in = p.getInputStream();
  66. BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf8"));
  67.  
  68. for (String inStr = null; (inStr = br.readLine()) != null;) {
  69. tableSql.append(inStr).append("<br>");
  70. }
  71.  
  72. in.close();
  73. br.close();
  74.  
  75. //处理错误的信息
  76. String errMsg = getErrMsg(p);
  77. if (errMsg != null) {
  78. throw new IOException(errMsg);
  79. }
  80.  
  81. return tableSql.toString();
  82. }
  83.  
  84.  
  85. /**
  86. * 备份数据库操作
  87. * @return BackupInfo备份状态对象
  88. * @throws IOException 文件读写错误
  89. */
  90. public static BackupInfo backup() throws IOException{
  91. File f = getMysqlDump();
  92. if(f == null){
  93. throw new FileNotFoundException("在lib路径下没有找到名为'mysqldump'的mysql工具,MysqlDumpUtil类的功能依赖此文件!");
  94. }
  95.  
  96. //构建远程数据库命令字符串
  97. StringBuilder cmdStr = new StringBuilder();
  98. cmdStr.append(" -u")
  99. .append(USERNAME)
  100. .append(" -p")
  101. .append(PASSWORD)
  102. .append(" -h")
  103. .append(IP)
  104. .append(" -P")
  105. .append(PORT)
  106. .append(" --ignore-table=")
  107. .append(DATABASENAME).append(".t_backup_database ")
  108. .append(" ").append(DATABASENAME);
  109.  
  110. //创建备份信息对象
  111. final BackupInfo bki = new BackupInfo();
  112. Runtime rt = Runtime.getRuntime();
  113. // 调用mysqldump的cmd命令
  114. final Process p;
  115. if(isWindows()){
  116. p = rt.exec(new String[]{"cmd","/c",f.getPath() + cmdStr.toString()});
  117. } else {
  118. p = rt.exec(new String[]{"sh","-c","cd "+ f.getParent() + " | mysqldump "+cmdStr.toString()});
  119. }
  120. //备份文件地址
  121. final File path = new File(getBackupPath().getPath() + "/" + new Date().toString().replaceAll(" |:", "") + ".sql");
  122. LOG.info(ClassUtil.getMethodName(),"备份文件地址 :" + path);
  123. //创建线程异步执行备份操作
  124. new Thread(){
  125. /* (non-Javadoc)
  126. * @see java.lang.Thread#run()
  127. */
  128. @Override
  129. public void run(){
  130. //得到远程数据库备份的流文件
  131. InputStream in = p.getInputStream();
  132. try {
  133. BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf8"));
  134. OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path), "utf8");
  135. //向指定地址写文件
  136. for(String str = null;(str = br.readLine()) != null;){
  137. writer.write(str+"/r/n");
  138. writer.flush();
  139. //记录当前写入字节数
  140. bki.setSize(str.getBytes().length + bki.getSize());
  141. }
  142.  
  143. bki.setPath(path.getPath());
  144. bki.setComplete(true);
  145. LOG.info(ClassUtil.getMethodName(),bki.toString());
  146. LOG.info(ClassUtil.getMethodName(),"备份文件完成!"+bki.isComplete());
  147.  
  148. in.close();
  149. br.close();
  150. writer.close();
  151.  
  152. //处理错误的信息
  153. String errMsg = getErrMsg(p);
  154. if(errMsg != null){
  155. bki.setError(true);
  156. bki.setComplete(true);
  157. bki.setErrMsg(errMsg);
  158. LOG.error(ClassUtil.getMethodName(), "备份过程中出现错误:" + errMsg);
  159. }
  160. LOG.info(ClassUtil.getMethodName(), "备份方法结束!");
  161. } catch (IOException e) {
  162. LOG.error(ClassUtil.getMethodName(),e.getMessage());
  163. bki.setComplete(true);
  164. bki.setError(true);
  165. bki.setErrMsg(e.getMessage());
  166. }
  167. }
  168. }.start();
  169.  
  170. return bki;
  171. }
  172.  
  173.  
  174. /**
  175. * 还原数据库
  176. * @param path 要还原的sql脚本文件路径
  177. * @throws IOException 文件读写出错
  178. */
  179. public static void loadData(String path) throws IOException{
  180. File f = getMysql();
  181. if(f == null){
  182. throw new FileNotFoundException("在lib路径下没有找到名为'mysql'的mysql工具,MysqlDumpUtil类的功能依赖此文件!");
  183. }
  184.  
  185. //构建远程数据库命令字符串
  186. StringBuilder cmdStr = new StringBuilder();
  187. cmdStr.append(" -u")
  188. .append(USERNAME)
  189. .append(" -p")
  190. .append(PASSWORD)
  191. .append(" -h")
  192. .append(IP)
  193. .append(" -P")
  194. .append(PORT)
  195. .append(" ").append(DATABASENAME).append("<").append(path);
  196.  
  197. Runtime rt = Runtime.getRuntime();
  198. // 调用mysqldump的cmd命令
  199. Process p = null;
  200. if(isWindows()){
  201. p = rt.exec(new String[]{"cmd","/c",f.getPath() + cmdStr.toString()});
  202. } else {
  203. p = rt.exec(new String[]{"sh","-c","cd "+ f.getParent() + " | mysql "+cmdStr.toString()});
  204. }
  205.  
  206. //处理错误的信息
  207. String errMsg = getErrMsg(p);
  208. if (errMsg != null) {
  209. throw new IOException(errMsg);
  210. }
  211. }
  212.  
  213.  
  214. /**
  215. * @author scottCgi
  216. * @since 2009-1-19
  217. * 封装了备份数据库时的状态信息
  218. */
  219. public static class BackupInfo{
  220. //备份是否完成
  221. private boolean isComplete;
  222. //备份文件大小
  223. private double size;
  224. //备份是否出错
  225. private boolean isError;
  226. //出错信息
  227. private String errMsg;
  228. //备份路径
  229. private String path;
  230.  
  231. public boolean isComplete() {
  232. return isComplete;
  233. }
  234. public void setComplete(boolean isComplete) {
  235. this.isComplete = isComplete;
  236. }
  237. public boolean isError() {
  238. return isError;
  239. }
  240. public void setError(boolean isError) {
  241. this.isError = isError;
  242. }
  243. public String getErrMsg() {
  244. return errMsg;
  245. }
  246. public void setErrMsg(String errMsg) {
  247. this.errMsg = errMsg;
  248. }
  249. public void setSize(double size) {
  250. this.size = size;
  251. }
  252. public double getSize() {
  253. return size;
  254. }
  255. public String getPath() {
  256. return path;
  257. }
  258. public void setPath(String path) {
  259. this.path = path;
  260. }
  261. }
  262.  
  263. /**
  264. * 获取mysqldump工具所的位置
  265. * @return 名为"mysqldump.exe"的文件路径
  266. */
  267. private static File getMysqlDump(){
  268. File f = null;
  269. try{
  270. if(isWindows()){
  271. f = new File(MysqlUtil.class.getResource("/../lib/mysqldump.exe").getPath());
  272. } else {
  273. f = new File(MysqlUtil.class.getResource("/../lib/mysqldump").getPath());
  274. }
  275.  
  276. } catch(NullPointerException e){}
  277.  
  278. return f;
  279. }
  280.  
  281. /**
  282. * 获取mysql工具所在的位置
  283. * @return 名为"mysql.exe"的文件路径
  284. */
  285. private static File getMysql(){
  286. File f = null;
  287. try{
  288. if(isWindows()){
  289. f = new File(MysqlUtil.class.getResource("/../lib/mysql.exe").getPath());
  290. } else {
  291. f = new File(MysqlUtil.class.getResource("/../lib/mysql").getPath());
  292. }
  293.  
  294. } catch (NullPointerException e){}
  295. return f;
  296. }
  297.  
  298. /**
  299. * 获取备份文件夹,没有则创建一个
  300. * @return 返回备份文件夹
  301. */
  302. private static File getBackupPath(){
  303. File f = new File(MysqlUtil.class.getResource("/").getPath());
  304. //获得web-info目录下的backup文件夹
  305. f = new File(f.getParent() + "/backup");
  306. LOG.info(ClassUtil.getMethodName(), f.getPath());
  307. if(!f.isDirectory()){
  308. f.mkdir();
  309. }
  310.  
  311. return f;
  312. }
  313.  
  314. /**
  315. * 获取cmd命令执行的错误信息
  316. * @param p Process对象
  317. * @return 错误信息字符串
  318. * @throws IOException 文件读写错误
  319. */
  320. private static String getErrMsg(Process p) throws IOException{
  321. StringBuilder errMsg = new StringBuilder();
  322. InputStream in = p.getErrorStream();
  323. BufferedReader br = new BufferedReader(new InputStreamReader(in,"utf8"));
  324. for(String inStr = null;(inStr = br.readLine()) != null;){
  325. errMsg.append(inStr).append("<br>");
  326. }
  327. in.close();
  328. br.close();
  329. return errMsg.length() == 0 ? null : errMsg.toString();
  330. }
  331.  
  332. /**
  333. * 判断是不是windows平台
  334. * @return true是Windows平台,false非Windows平台
  335. */
  336. private static boolean isWindows() {
  337. return System.getProperty("os.name").indexOf("Windows") != -1;
  338. }
  339.  
  340. }
Add Comment
Please, Sign In to add comment