【问题标题】:Exporting database to csv file with java使用java将数据库导出到csv文件
【发布时间】:2016-04-30 13:46:24
【问题描述】:

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

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

我得到以下异常: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 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();
    }
}

【问题讨论】:

    标签: java mysql database csv backup


    【解决方案1】:

    这是我用的:

    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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      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/ 可能会有所帮助!

      【讨论】:

        【解决方案3】:
        SELECT * FROM <MENTION_TABLE_NAME_HERE> INTO OUTFILE <FILE_NAME> FIELDS TERMINATED BY ',';
        

        例子:

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

        【讨论】:

          【解决方案4】:

          使用 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();
                  }
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2013-09-10
            • 1970-01-01
            • 2015-07-13
            • 2012-12-22
            • 2023-03-10
            • 1970-01-01
            • 2014-11-05
            • 1970-01-01
            相关资源
            最近更新 更多