我需要使用
java从mysql导出一个表.我试过用
public class automateExport {
public static void main(String[] argv) throws Exception {
String driverName = "com.mysql.jdbc.Driver";
Class.forName(driverName);
String serverName = "192.168.0.189";
String mydatabase = "ArchiveIndexer";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "username";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = connection.createStatement();
String filename = "c:/outfiless.txt";
String tablename = "D_Centre";
System.err.println("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
stmt.executeUpdate("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
// stmt.executeQuery("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
// stmt.execute("SELECT * INTO OUTFILE \"" + filename + "\" FROM " + tablename);
}
}
但是这就像扔错误一样
"Exception in thread "main" java.sql.SQLException: Can not issue SELECT via executeUpdate().
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1764)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1725)
at automateexceldatabase.automateExport.main(automateExport.java:38)
Java Result: 1"
最佳答案 这将有助于:
public class DatabaseToCSV {
public static void main(String[] args) {
String filename =
"C:\\Documents and Settings\\admin\\My Documents\\NetBeansProjects\\AutomateExcelDatabase\\myjdbcfile.csv";
try {
FileWriter fw = new FileWriter(filename);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(
"jdbc:mysql://192.168.0.189:3306/ArchiveIndexer"
, "username"
, "password"
);
String query = "select * from D_Centre";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append(',');
fw.append(rs.getString(4));
fw.append('\n');
}
fw.flush();
fw.close();
conn.close();
System.out.println("CSV File is created successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}