OpenCsv | SQL |只写标题,而不写表内容 [英] OpenCsv | SQL | Writes only the header and not the table content
问题描述
我试图通过Java执行一条SQL语句,并将结果写入.csv文件.
I am trying to execute an SQL statement through Java and write the results to a .csv file.
我正在使用 OJDBC.jar (v7)连接到Oracle 11g DB和 OPENCSV.jar (v3.8)来创建和写入Excel.
I am using OJDBC.jar (v7) to connect to Oracle 11g DB and OPENCSV.jar (v3.8) for creating and writing into the excel.
表格结果打印效果很好.我正在使用管道将记录中的所有列值分开.
Table result is printing very well. I am using pipe to separate all the column values in a record.
但是,在生成的csv文件中,我只能看到表的列名,而根本看不到任何数据!可能是什么原因?请帮忙.
However, on the generated csv file, i see only the column names of the table and no data at all! What might be the reason? Please help.
package test;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import com.opencsv.CSVWriter;
public class AllInOne
{
static String hostIP="255.255.255.255";
static String PortNum="1521";
static String ServiceName="SNAME";
static String un="USER";
static String pw="PWD";
static int columnCount;
static String row="";
public static void main(String[] args) throws Exception
{
String addr = "jdbc:oracle:thin:@"+hostIP+":"+PortNum+":"+ServiceName;
Class.forName("oracle.jdbc.OracleDriver");
Connection con = DriverManager.getConnection(addr,un,pw);
Statement stat = con.createStatement();
ResultSet rs = stat.executeQuery("select * from t_employee_info where rownum <6");
ResultSetMetaData resultSetMetaData = rs.getMetaData();
columnCount = resultSetMetaData.getColumnCount();
while (rs.next())
{
for (int i = 1; i <= columnCount; i++)
{
row += rs.getString(i) + "|";
}
System.out.println(row);
row = "";
}
FileWriter fw=new FileWriter("C:/Users/myName/Desktop/Folder/CSVfile.csv");
CSVWriter writer = new CSVWriter(fw);
writer.writeAll(rs,true);
writer.close();
fw.close();
stat.close();
con.close();
System.out.println("File Generated");
}
}
推荐答案
Shreyas,您已经对结果集进行了一次迭代.因此,您的选择是在RS上迭代到变量(例如|分隔值的列表)时将值存储起来,并将它们传递给CSV Writer上的方法.
Shreyas , you have already iterated over the result set once. So the choices you have are to store the values as you iterate over the RS to a variable (say a list of | delimited values) and pass them to a method on CSV Writer.
第二个选择是实际使用rs.first()(前提是您具有可滚动的结果集),然后将其传递给该方法.但是,这不是一个好习惯
A second option will be to actually use rs.first() (provided you have a scrollable result set) and then pass it to the method. This is however not a great practice
这篇关于OpenCsv | SQL |只写标题,而不写表内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!