我试图使用Java将MySql数据导出到一个文件,但我无法获取表头

时间:2012-01-12 06:54:44

标签: java mysql export

我能够将mysql导出到csv文件,但我没有获得表头,我希望在我的文件保存到系统时显示标题。

这是我正在使用的java代码:

import java.io.*;
import java.sql.*;

public class ExportData {

    public static void main(String args[]) {
        String Driver;
        Statement stmt;
        Driver = "com.mysql.jdbc.Driver";
        Connection con = null;

        try {
            Class.forName(Driver);
            con = DriverManager.getConnection(
                  "jdbc:mysql://localhost/emp", "root", "");
            if (!con.isClosed()) {
                System.out.println("Successfully connected to MySQL DataBase \n");
                stmt = con.createStatement();
                String filename = "C:/2.txt";
                String tablename = "employees";
                String sql;
                stmt.executeUpdate("SELECT * INTO OUTFILE \""
                        + filename + "\" FROM " + tablename);
            }
        } catch (Exception e) {
            System.err.println("Exception: " + e.getMessage());
        } finally {
            try {
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
            }
        }
    }
}

3 个答案:

答案 0 :(得分:1)

您需要使用ResultSetMetaData

答案 1 :(得分:0)

以下是作为评论附加到相关MySQL手册页的示例:

select 'idPago','fecha','lead','idAlumno','idTipoPago','idGpo',
    'idTaller','idDocente','pagoImporte','NoFactura','facturaImporte',
    'mes','formaPago','observaciones' union all
(select id_control_pagos, fecha, lead, id_alumno, id_concepto_pago, id_Gpo,id_Taller,
    id_docente, Pagoimporte, NoFactura, FacturaImporte, Mensualidad_No, FormaPago,
    Observaciones from control_pagos
    into outfile 'c:\\data.csv'
    FIELDS TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n');

简而言之,您必须手动添加列标签。

答案 2 :(得分:-3)

您无法使用executeUpdate()进行选择查询..... 使用executeQuery()