writer.writeAll(rs,true)创建一个空文件

时间:2019-03-12 14:08:31

标签: java csv opencsv

我正在使用opencsv从oracle数据库检索数据到结果集,然后到csv。我得到了检索到的结果,但是创建的csv为空? 输出为: Oracle JDBC驱动程序注册! 您做到了,现在就控制您的数据库! 216 18 160 18 480 18 384 18

package com.mkyong;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.io.*;
import java.io.IOException;
import java.sql.*;
import java.util.Scanner;
import com.opencsv.*;

public class OracleJDBCExample {
    public static void main(String[] argv) throws IOException {
        System.out.println("-------- Oracle JDBC Connection Testing ------");
        try {
             Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("Where is your Oracle JDBC Driver?");
            e.printStackTrace();
            return;
        }
        System.out.println("Oracle JDBC Driver Registered!");
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(
             "jdbc:oracle:thin:@//xyz.com:1521/xx", "USERNAME", "PWD");
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return;
        }
        if (connection != null) {
            System.out.println("You made it, take control your database now!"); 
            //step3 create the statement object  
            Statement stmt;
            try {
                stmt = connection.createStatement();
                 //step4 execute query           
                CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"));
                ResultSet rs=stmt.executeQuery("select unitsperpallet,defaultuom from tab where rownum < 5");  

                while(rs.next())
                {
                    System.out.println(rs.getInt(1) + " "+rs.getInt(2)); 
                }

                //set myResultSet to the results of your query here
                writer.writeAll(rs, true); 
                writer.flush();
                writer.close();
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
        } else {
            System.out.println("Failed to make connection!");
        }
    }

}

0 个答案:

没有答案