使用OpenCSV和Resultset

时间:2015-09-16 12:59:34

标签: java resultset opencsv

我正在尝试将oracle表导出到csv文件中,我创建了一个类,但输出文件格式如下:

12345 1002988846 1 薪水就在这里 67891 1009007305 0 Ma3ash在这里! 55555 1095003139 0 Ma3ash在这里! 77777 1023456789 1 薪水就在这里

这是班级:

import java.io.*;
import java.sql.*;
public class newway {

public void  mymethod() throws Exception {
try
{
Class.forName("oracle.jdbc.OracleDriver");

Connection conn= DriverManager.getConnection("jdbc:oracle:thin:@172.17.60.225:1521/FRSTEST", "TRASSET", "TRASSET");
conn.setAutoCommit(false);
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("Select * from Table1");


ResultSetMetaData rsmd = rs.getMetaData();
FileWriter cname = new FileWriter("D:\\asd.csv");
BufferedWriter bwOutFile = new BufferedWriter(cname);
StringBuffer sbOutput = new StringBuffer();
sbOutput.append("S_DATE");
bwOutFile.append(sbOutput);
bwOutFile.append(System.getProperty("line.separator"));
System.out.println("No of columns in the table:"+ rsmd.getColumnCount());

for (int i = 1; i <= rsmd.getColumnCount(); i++) 
{
String  fname = rsmd.getColumnName(i);
}

System.out.println();



while(rs.next())
{
for(int i=1; i<5;i++){  
System.out.print(rs.getString(i));
bwOutFile.append(rs.getString(i));
bwOutFile.append(System.getProperty("line.separator"));
}
bwOutFile.flush();
System.out.println();
} 
conn.close();

}
catch(SQLException se)
{
se.printStackTrace();
}
catch(Exception e)
    {
System.out.println("Unable to connect to database" +e);
}

}


}

我希望输出以逗号分隔,每行记录在一行中。 请帮忙吗?!

1 个答案:

答案 0 :(得分:0)

你在哪里使用openCSV?

这是来自openCSV中CSVWriter的测试之一,用于测试ResultSet中的写入记录。只需修改它以满足您的需求。

@Test
public void testResultSetWithHeaders() throws SQLException, IOException {
  String[] header = {"Foo", "Bar", "baz"};
  String[] value = {"v1", "v2", "v3"};

  StringWriter sw = new StringWriter();
  CSVWriter csvw = new CSVWriter(sw);
  csvw.setResultService(new ResultSetHelperService());

  ResultSet rs = MockResultSetBuilder.buildResultSet(header, value, 1);

  int linesWritten = csvw.writeAll(rs, true); // don't need a result set since I am mocking the result.
  assertFalse(csvw.checkError());
  String result = sw.toString();

  assertNotNull(result);
  assertEquals("\"Foo\",\"Bar\",\"baz\"\n\"v1\",\"v2\",\"v3\"\n", result);
  assertEquals(2, linesWritten);
}