简体   繁体   中英

Groovy Better Approach to create comma separated string from Database Select Query

I am trying to connect to oracle database table and pull the data and form the result in the form of comma separated values. I have written a sample code which works fine but wanted to have a better approach if the query is associated with more tables (joins), then the time is taken to get the output is more. Is there any better way of improving the performance.

import groovy.sql.Sql;
import java.sql.ResultSet;

def temp="";
def temp1="";
sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:XE","username", "password", "oracle.jdbc.driver.OracleDriver")
sql.eachRow("select empid, empname FROM employee") {
    temp1=it.toRowResult().values().join(", ")
    if(temp=="") {
        temp=temp1;
    }else{
        temp=temp+"\n"+temp1
    }          
}
 CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), ',');
 Boolean includeHeaders = true;

 java.sql.ResultSet myResultSet = .... //your resultset logic here

 writer.writeAll(myResultSet, includeHeaders);

 writer.close();

You can select empid || ', ' || empname as NewValue FROM employee in your query, then SQL work for you a little bit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM