最近遇到一个需求要在linux下用java 调用mysql客户端远程登陆mysql服务器,从客户端机器导入mysql脚本,从mysql服务器端导出表中的数据。以下是用到的主要方法:
Java 代码
/**
* 导入数据
* @param 脚本的地址和名称
* @return 是否成功
*/
public static boolean importDb(String filepath) {
boolean flag= true ;
System.out.println("filepaht = " + filepaht); //脚本地址
String[] cmd = {"cat " +filepaht+ "| /usr/mysql/bin/mysql -uroot -p123456 --default-character-set=gbk -h142.16.254.2 test" };
try {
Process process = Runtime.getRuntime().exec(
new String[]{
"sh" ,
"-c" ,
cmd[0 ]});
BufferedReader inputBufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null ;
while ((line = inputBufferedReader.readLine()) != null ) {
System.out.println(line);
}
try {
process.waitFor();
} catch (InterruptedException e) {
flag=false ;
e.printStackTrace();
}
} catch (IOException e) {
flag=false ;
e.printStackTrace();
}
return flag;
}
Java 代码
/**
* 导出数据
* @param sql:要执行的查询语句
*@param filename:生成的文件地址和文件名
* @return 是否成功
*/
public static boolean exportDb(String sql,String filename) {
boolean flag= true ;
// System.out.println("filename = " + filename);
String[] cmd = {"/usr/mysql/bin/mysql -uroot -p123456 --default-character-set=gbk -h142.16.254.2 test -e/"" +sql+ "/" > " +filename};
System.out.println("cmd[0] = " + cmd[ 0 ]);
try {
Process process = Runtime.getRuntime().exec(
new String[]{
"sh" ,
"-c" ,
cmd[0 ]});
BufferedReader inputBufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null ;
while ((line = inputBufferedReader.readLine()) != null ) {
System.out.println(line);
}
try {
process.waitFor();
} catch (InterruptedException e) {
flag=false ;
e.printStackTrace();
}
} catch (IOException e) {
flag=false ;
e.printStackTrace();
}
return flag;
}
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/doney_dongxiang/archive/2009/09/19/4569934.aspx