问题描述:

I am able to export mysql to csv file but i am not getting table headers, I want headers to be displayed when my file gets saved to my system.

This is the java code which I am using:

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) {

}

}

}

}

网友答案:

Here's an example that was attached as a comment to the relevant MySQL manual page:

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

In short, you have to add the column labels by hand.

网友答案:

You need to use ResultSetMetaData

网友答案:

you cannot use executeUpdate() for select queries..... use executeQuery()

相关阅读:
Top