一、起因
无意中发现了一个有趣的操作,于是就记录下来;
二、经过
请观察以下代码:
package com.liuzm;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
public class RunTimeTest {
public static void main(String[] args) {
String[] sb = new String[3];
sb[0] = "cmd";
sb[1] = "/c";
sb[2] = new StringBuilder("mysql")
.append(" -u").append("root")
.append(" -p").append("root")
.append(" -h").append("127.0.0.1")
.append(" -P").append("3306")
.append(" --default-character-set=UTF8")
.toString();
Process process = null;
try {
process = Runtime.getRuntime().exec(sb);
} catch (IOException e) {
e.printStackTrace();
}
OutputStream os = process.getOutputStream();
String switchCmd = new StringBuilder("use ").append("my_test").toString();
//获取truncate的命令语句
String truncateCmd = new StringBuilder("TRUNCATE TABLE ").append("person").toString();
OutputStreamWriter writer = new OutputStreamWriter(os);
try {
writer.write(switchCmd+ System.getProperty("line.separator") +truncateCmd);
writer.flush();
writer.close();
os.close();
int truncateRes = process.waitFor();
if(truncateRes == 0){
System.out.println("------表数据清理结束------");
} else {
System.out.println("表数据清理失败,truncateProcess.waitFor()返回值为:" + truncateRes);
}
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}
这是我模拟的一段代码,拿来直接可以用,记得改一下用户名和密码;如果在Linux环境下请把改为sb[1] = “-c”;先看一下这几个重载方法:
在看一下源码:
这几个方法实现都是exec(String command, String[] envp, File dir),可以回忆一下线程池;点进去看一下:
平时用的很少,就不往下看了;大概了解一下即可;
三、使用sql清空
表数据:
mapper接口
int TrancateTable();
mapper.xml
<update id="TrancateTable">
truncate table user_table;
</update>
测试类
@Test
public void test4(){
userMapper.TrancateTable();
}
控制台输出
==> Preparing: truncate table user_table;
==> Parameters:
<== Updates: 0
数据库