大家好我试图将销售表(Oracle)中的所有交易打印到文本文件中。不幸的是,它只写了一条记录,而该表有许多符合标准的记录。有人可以告诉我这是什么问题吗?
这是我的代码:
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj == btnSave) {
Connection conn = null;
String receno = Lrecno.getText();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "MUNGAI", "gatungo87");
Statement st = conn.createStatement();
String recp = "select PART_DESC, QUNTY, UNIT_SALE, TOTAL_SALE from sales where session_id = '" + receno + "'";
ResultSet rs = st.executeQuery(recp);
while (rs.next()) {
File f = new File("Sale Receipts");
f.mkdir();
BufferedWriter bw = new BufferedWriter(new FileWriter("Sale Receipts/Sale" + Lrecno.getText() + ".TXT"));
String receipt = rs.getString("PART_DESC") + " " + rs.getString("QUNTY") + " "
+ rs.getString("UNIT_SALE") + " " + rs.getString("TOTAL_SALE");
String[] rece = receipt.split("\n");
for (int i = 0; i < rece.length; i++) {
bw.write(receipt);
bw.flush();
bw.newLine();
}
JOptionPane.showMessageDialog(this, "Item sold successfully",
"Success", JOptionPane.PLAIN_MESSAGE);
}
} catch (Exception ad) {
JOptionPane.showMessageDialog(this, ad,
"Error", JOptionPane.PLAIN_MESSAGE);
}
}
答案 0 :(得分:3)
您正在为ResultSet
中while
循环中的每条记录打开文件,因此文件被覆盖,只有当您处理完所有行时,最后一条记录仍然存在来自ResultSet
。
将BufferedWriter
移到while循环之外,并将其与结果集,语句和连接一起关闭。
答案 1 :(得分:2)
你可以试试这个:
File f = new File("Sale Receipts");
f.mkdir();
BufferedWriter bw = new BufferedWriter(new FileWriter("Sale Receipts/Sale" + Lrecno.getText() + ".TXT"));
String receipt="";
while (rs.next()) {
receipt += rs.getString("PART_DESC") + " " + rs.getString("QUNTY") + " "
+ rs.getString("UNIT_SALE") + " " + rs.getString("TOTAL_SALE");
String[] rece = receipt.split("\n");
for (int i = 0; i < rece.length; i++) {
bw.write(receipt);
bw.flush();
bw.newLine();
}
JOptionPane.showMessageDialog(this, "Item sold successfully",
"Success", JOptionPane.PLAIN_MESSAGE);
}
您的错误是您创建的表中的每一行都将其写入文件,然后您继续覆盖同一文件。
正确的方法是通过迭代ResultSet来构建String,然后将String写入文件
<强>更新强>
考虑使用StringBuilder对象更改String以解决性能问题。
StringBuilder receipt = new StringBuilder();
while (rs.next()) {
receipt.append( rs.getString("PART_DESC") + " " + rs.getString("QUNTY") + " "
+ rs.getString("UNIT_SALE") + " " + rs.getString("TOTAL_SALE"));
receipt.append("\n");
JOptionPane.showMessageDialog(this, "Item sold successfully",
"Success", JOptionPane.PLAIN_MESSAGE);
}
bw.write(receipt.toString());
bw.flush();
bw.newLine();