日期:2014-05-20  浏览次数:20761 次

如何用java实现mysql数据库的导入导出啊
如何用java实现mysql数据库的导入导出啊,导出什么格式都行~ sql,或者xls的啊,经理新给我安排的任务,可是我想了两天也不会啊!急!!!求各位大虾们高手帮忙啊,给出现成的代码就行啦

------解决方案--------------------
探讨
Runtime.getRuntime().exec("mysqldump –uroot –p1234  test>f:\test.sql");
这样写对嘛?我检查了一下F盘,没有生成test.sql文件啊,可是这个命令在cmd里运行就可以在F盘生成
test.sql文件呢,在程序里就不对了?我哪里写的有问题嘛?

------解决方案--------------------
public class mysqldao {

public static void main(String args[]) {

try {
Runtime javaRuntime = Runtime.getRuntime();
javaRuntime.exec("cmd.exe /C cmd /C mysqldump -u root -proot test>d:/test.sql");
}catch(Exception e) {

}
}

}
已编译通过
------解决方案--------------------
探讨
导出成Excel需要用一个jar包,jxl,是专门用java生成Excel文件的。
具体我给你说下怎么做吧,你先把数据从数据库中查询出来保存到javabean中,一条数据一个bean,然后放到list中。这边写一个专门写Excel文件的小工具类,把这个list传给它,在里面循环开,一条一条记录的写到Excel中去。

具体的API和例子程序网上很多,自己去找找吧,baidu一下很多的~~
怎么创建一个工作目录,怎么写数字,写文字,写图片等等API里都有方法,直接调用,传对参数就行。

------解决方案--------------------
Java code

    /**
     * 弹出保存对话框,获得保存路径和文件名,用户没有选择则返回null
     * @param parentFrame 父窗体
     * @return 文件名
     */
    public String getPath(Component parentFrame) {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("D://"));// 默认打开路径
        // 设置过滤文件格式
        chooser.setFileFilter(new FileFilter() {
            public boolean accept(File file) {
                if (file.isDirectory()) {
                    return true;
                }
                if (file.getName().endsWith(".sql")) {
                    return true;
                }
                return false;
            }
            public String getDescription() {
                return "*.sql";
            }
        });
        int i = chooser.showSaveDialog(parentFrame);
        String fileName = null;
        if (JFileChooser.APPROVE_OPTION == i) {
            File file = chooser.getSelectedFile();
            if (file.exists()) {
                int t = JOptionPane.showConfirmDialog(parentFrame,
                        "该文件已存在,是否覆盖?", "是否覆盖?", JOptionPane.OK_CANCEL_OPTION);
                if (t != JOptionPane.OK_OPTION) {
                    return getPath(parentFrame);
                }
            }
            if (file.toString().endsWith(".sql")) {
                fileName = file.toString();
            } else {
                fileName = file.toString() + ".sql";
            }
        }
        return fileName;
    }