How can I print column sections from SQL to Java to CSV?

I have set up a MySQL database, my connection works, and I've somewhat got a handle on how to retrieve data from the database using ResultSet. The issue I'm currently having is that the assignment calls for certain columns from a few different tables to be printed in CSV format along with replacing some values that meet certain conditions; i.e., if the cost of a plane ticket for a particular flight is under a certain price, replace the cost with "LOW!" in that part of the CSV file. Here's what I've got:

public void generate() throws IOException, SQLException{

    FileWriter fw = new FileWriter("datamine.csv");
    PrintWriter out = new PrintWriter(fw);
    Statement st = conn.createStatement();

    out.println("Airline,FlightNumber,Source,Destination,DayOfWeek,Seats,Daysbefore,Price");

    //ResultStatements here

    out.flush();
    out.close();
    fw.close();

}

I know how to query the DB, and I think I can figure out how to union the columns from tables that I need, but that will just print everything in the column. Is there a way to iterate through the columns, evaluate the value for conditionals, and then append it to the output file?

Answers


You need a while loop, and an if test.

while (rs.next()) {

    String airline = rs.getString(1);
    ...
    BigDecimal price = rs.getBigDecimal(8);
    if (price.compareTo(limit) < 0) {
        csvFile.print("LOW!");
    }
    else {
        csvFile.print(price);
    }
}

Need Your Help

Removing duplication of code for calls to “RouteCollection.MapRoute()” and “AreaRegistrationContext.MapRoute()”

c# asp.net-mvc refactoring

Basically as the title says when using Areas in ASP.NET MVC2.0 I've ended up with the following "MapRoute" handling code being duplicated for "RouteCollection" and AreaRegistrationContext". Both

UIAlert View Objective C - Opening app store link

objective-c cocoa-touch ios app-store uialertview

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"An Alert!"