gpt4 book ai didi

java结果集只写入一行而不是全部选择到.csv中

转载 作者:行者123 更新时间:2023-11-30 00:21:59 26 4
gpt4 key购买 nike

我有一个 java 函数,旨在从名为“readyList”的 jlist 中获取字符串,并从 mysql 工作台表中提取数据,以便为 .csv 文件中的每个字符串写入一行。使用当前代码,它可以像我预期的那样一次成功地提取数据,但它只写入最后一行而不是所有行。我想将所有行写入 .csv 文件中。请帮忙!

int[] selectedIx = readyList.getSelectedIndices(); 
for (int i = 0; i < selectedIx.length; i++) {
// while (i < selectedIx.length) {
Object sel = readyList.getModel().getElementAt(selectedIx[i]);

Statement s1 = DBConnect.connection.createStatement();
String selTable01 = "SELECT Sku As s, Qty As q, Orig_Retail As prce, Orig_Sku As orgsk, Store As strcd "
+ "FROM completed_lines WHERE Form_Name = '" + sel + "' AND Warranty = 'true'";

s1.execute(selTable01);
try (ResultSet rs01 = s1.getResultSet()) {
fWriter = new FileWriter("Exports/Transfers/" + /* frmNm.replace(":", "_") */"EBW_" + GtDates.fdate + ".csv", false);
writer = new BufferedWriter(fWriter);
String header = "slip_number,slip_type,out_store,in_store,item_number,quantity,price,comment,to_num";
writer.write(header);
writer.newLine();
while (rs01.next()) {
String strcode = rs01.getString("strcd");
String sku = rs01.getString("s");
String qty = rs01.getString("q");
String price = rs01.getString("prce");
String orgsku = rs01.getString("orgsk");
//System.out.println(frmNm.split("_")[1] + qty + "," + sku + "," + vendor + "," + desc1 + "," + reas + "," + descdmg + "," + orgR + "," + nwsku + "," + desc2 + "," + qtyI);
String line = ""+","+"out"+","+strcode+","+"RTV"+","+sku+","+qty+","+price+","+"EBW"+","+orgsku;
writer.write(line);
writer.newLine();

}
}
// JOptionPane.showMessageDialog(frame, "All Data from Selected Forms has been Exported");
}
// FormCompelted();

writer.close();

}

}

最佳答案

此代码存在一些问题。您只得到最后一个结果的原因是因为这一行:

fWriter = new FileWriter("Exports/Transfers/" + /* frmNm.replace(":", "_") */"EBW_" + GtDates.fdate + ".csv", false);

该行位于您的循环内。作为最后一个参数的 false 告诉 FileWriter 不要追加。换句话说,false 表示覆盖该文件(如果存在)。由于这是在循环中,因此每个结果都会覆盖最后一个结果创建的文件。您应该在循环之外创建 FileWriter ,可能是在尝试使用资源时。这将允许您删除 writer.close() 调用,该调用无论如何都应该位于 finally block 中。

与您原来的问题无关,但您应该注意:您将在每次循环迭代时创建一个新的Statement。这可能是一项昂贵的操作。您应该使用 PreparedStatement反而。在循环外部创建它,然后只需设置参数并在循环内部执行它。它还实现了 AutoCloseable,因此您也可以尝试使用资源来创建它,可能与您在其中创建 FileWriter 的资源相同。

关于java结果集只写入一行而不是全部选择到.csv中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23161790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com