我试图导出oracle表到csv文件,我已经创建了一个类这样做,但输出文件格式如下:
1234510029888461薪水在这里6789110090073050Ma3ash在这里!5555510950031390Ma3ash在这里!7777710234567891工资在这里
下面是类:
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);
}
}
}
我希望输出用逗号分隔,并且每个记录在一行中。请帮忙?!
您在哪里使用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);
}