I am trying to execute an SQL statement through Java and write the results to a .csv file.
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.
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");
}
}