简体   繁体   English

用Groovy更好的方法从数据库选择查询创建逗号分隔的字符串

[英]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. 我正在尝试连接到oracle数据库表并提取数据并以逗号分隔值的形式形成结果。 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 || 您可以选择empid || ', ' || ','|| empname as NewValue FROM employee in your query, then SQL work for you a little bit empname作为NewValue FROM员工在您的查询,然后SQL为您工作一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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