我正在使用以下 Java 代码从MySQL表中获取数据作为CSV文件。
使用此命令,我可以从MySQL获取数据作为 CSV文件:
mysql -uuname -ppassword BR_RNCM -e'select * from Inward where inwarddate between "2012-08-21 00:00:00" and "2012-08-21 23:59:59"'>/home/praveen/downloadfile.csv
如何优化我的代码\算法?
我的代码是:
package com.mypackage.CAF.APController;
import com.rajsoft.CAF.util.DB2Connection;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InwardDataDownload extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection con = null;
ResultSet rs = null;
Statement st = null;
String date1 = null;
String date2 = null;
date1 = request.getParameter("fromdate");
date2 = request.getParameter("todate");
System.out.println("Date1 : " + date1 + "Date2 : " + date2);
try {
response.setContentType("text/csv");
out.write("CAF");
out.write(',');
out.write("MDN");
out.write(',');
out.write("CRT CODE");
out.write(',');
out.write("DISTRIBUTOR NAME");
out.write(',');
out.write("CLUSTER");
out.write(',');
out.write("MNP");
out.write(',');
out.write("LOT NO");
out.write(',');
out.write("INDEX NO");
out.write(',');
out.write("BOX NO");
out.write(',');
out.write("USER");
out.write(',');
out.write("INWARD DATE");
out.write('\n');
query = "select * from Inward where inwarddate between '" + date1 + "' and '" + date2 + "';";
con = (Connection) new DB2Connection().getDatabaseConnection();
st = con.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
out.write(rs.getString(1));
out.write(',');
out.write(rs.getString(2));
out.write(',');
out.write(rs.getString(3));
out.write(',');
out.write(rs.getString(4));
out.write(',');
out.write(rs.getString(5));
out.write(',');
out.write(rs.getString(6));
out.write(',');
out.write(rs.getString(7));
out.write(',');
out.write(rs.getString(8));
out.write(',');
out.write(rs.getString(9));
out.write(',');
out.write(rs.getString(10));
out.write(',');
out.write(rs.getString(11));
out.write('\n');
}
response.setContentType("application/download");
response.setHeader("Content-disposition", "attachment; filename =InwardData.csv");
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}