使用java将数据库导出到csv文件

时间:2016-01-24 05:06:57

标签: java mysql database csv backup

所以我在互联网上找到了这个代码,基本上它可以做的是从db备份所有表,我的问题就在这一行:

res = st.executeQuery("select * from xcms." + tableName);
  

我得到以下的excpetion异常:SQLException信息

xcms是什么。代表?还有什么可以放在这里?

res = st.executeQuery("select * from " + tableName);

顺便说一句,如果我擦除xcms。并把它像这样^,我只能保存第一个表而不是所有的表,thx

源代码网页:

https://gauravmutreja.wordpress.com/2011/10/13/exporting-your-database-to-csv-file-in-java/#comment-210

public class ExporttoCSV {
public static void main(String[] args) {
    Connection con = null;
    String url = "jdbc:mysql://localhost:3306/";
    String db = "gg";
    String driver = "com.mysql.jdbc.Driver";
    String user = "root";
    String pass = "";
    FileWriter fw;

    try {
        Class.forName(driver);
        con = DriverManager.getConnection(url + db, user, pass);
        Statement st = con.createStatement();
        ResultSet res = st.executeQuery("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'gg'");
        List<String> tableNameList = new ArrayList<String>();
        while (res.next()) {
            tableNameList.add(res.getString(1));
        }
        String filename = "C:\\Users\\Angel Silva\\Documents";
        for (String tableName : tableNameList) {
            int k = 0;
            int j = 1;
            System.out.println(tableName);
            List<String> columnsNameList = new ArrayList<String>();
            res = st.executeQuery("select * from " + tableName);

            int columnCount = getColumnCount(res);

            try {
                 fw = new FileWriter("C:\\Users\\Angel Silva\\Documents\\popo1121.csv");

                for (int i = 1; i <= columnCount; i++) {
                    fw.append(res.getMetaData().getColumnName(i));
                    fw.append(",");

                }
                fw.append(System.getProperty("line.separator"));

                while (res.next()) {
                    for (int i = 1; i <= columnCount; i++) {
                        if (res.getObject(i) != null) {
                            String data = res.getObject(i).toString();
                            fw.append(data);
                            fw.append(",");
                        } else {
                            String data = "null";
                            fw.append(data);
                            fw.append(",");
                        }
                    }
                    fw.append(System.getProperty("line.separator"));
                }
                fw.flush();
                fw.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        con.close();
    } catch (ClassNotFoundException cnfe) {
        System.err.println("Could not load JDBC driver");
        cnfe.printStackTrace();
    }catch (SQLException sqle) {System.err.println("SQLException information");}
}

public static int getRowCount(ResultSet res) throws SQLException {
    res.last();
    int numberOfRows = res.getRow();
    res.beforeFirst();
    return numberOfRows;
}
public static int getColumnCount(ResultSet res) throws SQLException {
    return res.getMetaData().getColumnCount();
}

}

5 个答案:

答案 0 :(得分:1)

xms代表数据库名称,在Java程序的Connection中,您已经在建立与数据库的连接:

(DriverManager.getConnection(url + db, user, pass);

字符串db是要连接的数据库的名称。

因此不需要xms.,仅使用此查询为例:

"SELECT * FROM "+tableName+";"

这是在您连接的数据库中执行的,例如代码中的gg

用于编写CSV文件chillyfacts.com/export-mysql-table-csv-file-using-java/可能会有所帮助!

答案 1 :(得分:0)

将Mysql表导出到文件的简单方法。 SELECT INTO OUTFILE将生成CSV文件。

String filename = "d:/outfile.csv";
String tablename = "abc";
stmt.executeQuery("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);

答案 2 :(得分:0)

SELECT * FROM <MENTION_TABLE_NAME_HERE> INTO OUTFILE <FILE_NAME> FIELDS TERMINATED BY ',';

示例:

SELECT * FROM topic INTO OUTFILE 'D:\5.csv' FIELDS TERMINATED BY ',';

答案 3 :(得分:0)

这是我使用的:

public void sqlToCSV (String query, String filename){

       log.info("creating csv file: " + filename);

       try {

         FileWriter fw = new FileWriter(filename + ".csv");
         if(conn.isClosed()) st = conn.createStatement();
         ResultSet rs = st.executeQuery(query);

         int cols = rs.getMetaData().getColumnCount();

         for(int i = 1; i <= cols; i ++){
            fw.append(rs.getMetaData().getColumnLabel(i));
            if(i < cols) fw.append(',');
            else fw.append('\n');
         }

         while (rs.next()) {

            for(int i = 1; i <= cols; i ++){
                fw.append(rs.getString(i));
                if(i < cols) fw.append(',');
            }
            fw.append('\n');
        }
        fw.flush();
        fw.close();
        log.info("CSV File is created successfully.");
        conn.close();
    } catch (Exception e) {
        log.fatal(e);
    }
}

答案 4 :(得分:0)

使用opencsv依赖项以最少的代码行将SQL数据导出到CSV。

import com.opencsv.CSVWriter;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CsvWriter {

    public static void main(String[] args) throws Exception {

        CSVWriter writer = new CSVWriter(new FileWriter("filename.csv"), '\t');
        Boolean includeHeaders = true;
         Statement statement = null;
         ResultSet myResultSet = null;
         Connection connection = null;
        try {
            connection = //make database connection here

            if (connection != null) {

                statement = connection.createStatement();
                myResultSet = statement.executeQuery("your sql query goes here");

                writer.writeAll(myResultSet, includeHeaders);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}