将sql查询结果导出到csv或excel
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将sql查询结果导出到csv或excel相关的知识,希望对你有一定的参考价值。
我想将sql查询的结果写入csv或excel文件,并将其保存在特定的文件夹中。我想知道是否可以使用java程序实现,可以重用任何sql查询结果。我会还想知道这是否可以用于不同类型的数据库(oracle,mysql,MS sql server等)。我打算将保存的文件附加到电子邮件中(这可能直接将sql查询结果导出到电子邮件中)。请帮忙。
答案
使用openCSV API,您可以在csv文件中导出数据。
CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), ' ');
Boolean includeHeaders = true;
java.sql.ResultSet myResultSet = .... //your resultset logic here
writer.writeAll(myResultSet, includeHeaders);
writer.close();
另一答案
最简单的解决方案
主要方法
private List<String> resultSetArray=new ArrayList<>();
private String username =""; // Enter DB Username
private String password = ""; // Enter DB password
private String url = ""; // Enter DB URL
Connection connection=DriverManager.getConnection(url,user,pwd);
public static void main(String args[]) throws Exception{
fetchDataFromDatabase("SQL queries", connection);
printToCsv(resultArray);
}
从数据库中获取数据
下面的代码计算表中的列数,并存储在结果数组中。
private void fetchDataFromDatabase(String selectQuery,Connection connection) throws Exception{
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(selectQuery);
int numCols = rs.getMetaData().getColumnCount();
while(rs.next()) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= numCols; i++) {
sb.append(String.format(String.valueOf(rs.getString(i))) + " ");
}
resultSetArray.add(sb.toString());
}
} catch (SQLException e) {
LOGGER.error("Sql exception " + e.getMessage());
}
}
printToCsv
public static void printToCsv(List<String> resultArray) throws Exception{
File csvOutputFile = new File(file_name);
FileWriter fileWriter = new FileWriter(csvOutputFile, false);
for(String mapping : resultArray) {
fileWriter.write(mapping + "
");
}
fileWriter.close();
}
另一答案
这是一个例子:
import java.io.*;
import java.sql.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
public class ExcelFile {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root");
PreparedStatement psmnt = null;
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("Select * from student");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Excel Sheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("Roll No");
rowhead.createCell((short) 1).setCellValue("Name");
rowhead.createCell((short) 2).setCellValue("Class");
rowhead.createCell((short) 3).setCellValue("Marks");
rowhead.createCell((short) 4).setCellValue("Grade");
int index = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow((short) index);
row.createCell((short) 0).setCellValue(rs.getInt(1));
row.createCell((short) 1).setCellValue(rs.getString(2));
row.createCell((short) 2).setCellValue(rs.getString(3));
row.createCell((short) 3).setCellValue(rs.getInt(4));
row.createCell((short) 4).setCellValue(rs.getString(5));
index++;
}
FileOutputStream fileOut = new FileOutputStream("c:\excelFile.xls");
wb.write(fileOut);
fileOut.close();
System.out.println("Data is saved in excel file.");
rs.close();
connection.close();
} catch (Exception e) {
}
}
}
另一答案
这是我的解决方案。要在主类中插入的代码:
import java.io.*;
import java.sql.*;
import com.company.*;
/**
* Created by MAXNIGELNEGRO
*/
String[] filePath = new String[] {"C:\Users\Documents\MyFile.csv"};
String[] driverDB = new String[] {"oracle.jdbc.driver.OracleDriver"};
String[] stringConnDB = new String[] {"jdbc:oracle:thin:@//127.0.0.1:1881/mydb"};
String[] userDB = new String[] {"pippo"};
String[] passDB = new String[] {"pluto"};
String[] charSep = new String[] {";"};
Boolean colomn= new Boolean (true);
String[] queryDB = new String[] {"select * FROM MYQUERY"};
try{
System.out.println("---------------File exist?------------" + filePath[0]);
File fileTemp = new File(filePath[0].toString());
if (fileTemp.exists()){
fileTemp.delete();
System.out.println("---------------DELETE FILE------------" + filePath[0] );
}
System.out.println("QUERY: ---->"+ queryDB[0].toString());
exportQueryToCsv exp = new exportQueryToCsv();
exp.exportQueryToCsv(filePath,driverDB,stringConnDB,userDB,passDB,queryDB, colomn,charSep);
if (fileTemp.exists()){
System.out.println("---File created---" + filePath[0]);
}
}
catch(Exception e){
e.printStackTrace();
}
核心课程:
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Created by MAXNIGELNEGRO
*/
public class exportQueryToCsv {
public exportQueryToCsv(){}
public static void exportQueryToCsv (String[] filename, String[] driverDB, String[] connDB
, String[] userDB, String[] passDB, String[] queryDB, Boolean intestaFile
, String[] charSep) throws SQLException, IOException {
Statement stmt=null;
ResultSet rset=null;
Connection conn=null;
try { DBConn connessione = new DBConn();
conn=connessione.connect(driverDB[0],connDB[0],userDB[0],passDB[0]);
conn.setAutoCommit(false);
stmt = conn.createStatement();
rset = stmt.executeQuery(queryDB[0]);
ExportData2CSV csv = new ExportData2CSV();
csv.ExportData2CSV(rset,filename[0],intestaFile,charSep[0]);
csv.createFileCsv();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if (stmt != null) {stmt.close();}
if (conn != null) {conn.close();}
if (rset != null) {rset.close();}
}
}
}
这是用于连接数据库的类DBConn
import java.sql.*;
/**
* Created by MAXNIGELNEGRO
*/
public class DBConn {
public DBConn() {
}
public Connection connect(String driverDB, String db_connect_str, String db_userid, String db_password) {
Connection conn;
try {
Class.forName(driverDB).newInstance();
conn = DriverManager.getConnection(db_connect_str, db_userid, db_password);以上是关于将sql查询结果导出到csv或excel的主要内容,如果未能解决你的问题,请参考以下文章
如何将SQL server 2008 里的查询结果导出到 Excel 表内?