当前位置: 代码迷 >> SQL >> 可以便利的将SQL语句的执行结果显示成表格结果的JAVA类,可以用于不同的数据显示
  详细解决方案

可以便利的将SQL语句的执行结果显示成表格结果的JAVA类,可以用于不同的数据显示

热度:98   发布时间:2016-05-05 13:09:52.0
可以方便的将SQL语句的执行结果显示成表格结果的JAVA类,可以用于不同的数据显示

说明:

在做网络程序的时候,我们总是需要将数据从数据库里面读出来,并将其显示,如果每次都去写,那就有点麻烦,程序员最讨厌的事就是做无用的重复功,至少我是其中的一员,在一个项目中做了一个这个东东,感觉用起来还是很方便的,

这是一个通用的将查询结果显示成表格的类,你想显示多少,你只需要在你的SQL语句里面的控制就可以,可以做到随心所欲了。

主要原理就是根据你的SQL语句,根据rs.getMetaData();及rsmd.getColumnName(j);取得列名,然后再把内容循环读出来就可以了,在读取内容的过程中,加入表格元素控制,然后就可以将取得到的内容转换成表格形式。你可以将我注释了的将英文字段换成中文的函数补充完整,这样你的图上显示就是中段了,我这里就不把那个函数写出来,因为很简单,这里也有这么多的东西了。不过,我附到最后面,以及翻页要用的一个JS函数,都附在最后面。

这是一张运行效果图:

下面是源代码,有点长,如果你觉得下面的太长了,太难看,你可以到这里下载这个JAVA源文件,这里有一个示例,如下:

示例:

/**

?* 这是一个可以把执行结果返回成表格的形式的类,在JSP页面只需要一个打印语句就可以把结果查询结果

?* 打印出来。通用性比较强,不过,性能上面我没有去考虑@——@

?* 这里一个简单的示例,不过,要放在JSP页面里面使用:

?* GetSearchResultByTableFormat get=new GetSearchResultByTableFormat();

?* get.setTableTitle(" ");

?* get.setEditUrl("purchaseInformation_edit.do");

?* get.setVerify(true);//把需要通过验证标志设为true

?* get.setVerifyURL("PassVerify_PurchaseInformation.do");

?* String sql="Select * From table";

?* //取得当前的页号

?* int currentPage;

?* try{

?*????? currentPage=Integer.parseInt(request.getParameter("page"));

??? }catch(NumberFormatException e)

??? {

??????? currentPage=1;

??????? try{

??????????? currentPage=(Integer)(request.getAttribute("page"));

??????????? //out.println("当前页:"+currentPage);

??????? }catch(Exception e1)

??????? {

??????????? currentPage=1;???????????

??????? }

??? }

?* //取得当前的页号OK

?* get.setDelUrl("purchaseInformation_del.do?page="+currentPage+"&");

?* int pageSize=20;

?* String pageUrl="purchaseInformation_verify.jsp";

?* get.setCurrentPageUrl(pageUrl);

?* get.setViewUrl("purchaseInformation_View.do");

?* //把取得的查询结果打印出来就OK

?* out.println(get.getResult_withTableFormat(sql,currentPage,pageSize,true));

?* 上面的操作看起来有点烦,要设置的东西,也比较多,不过,这是从通用性上考虑的,并且多考虑了

?* 一些功能,如把编辑、删除、审核等的链接都加上了,如果你只是一个简单的显示的,你可以稍稍更

?* 改一些,就成为你需要的了。更改也很简单,把这个方法getExecuteResult_withTableFormat

?* 改这一下就可以了。

?* 欢迎常回家看看:http://blog.csdn.net/fenglibing

?*/

源代码:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;

?

public class GetSearchResultByTableFormat {

?

??? public GetSearchResultByTableFormat() {

??????? conn_init();

??? }

??? Connection conn;

??? Statement st;

??? int currentPage; //当前页号

??? int pageSize; //每页显示记录条数

??? int totalPage; //总共页数

??? int previousPage; //前一页页号

??? int nextPage; //下一页页号

??? int columnCount; //总共列数

??? int totalRecord; //总记录数

??? String tableTitle; //大标题,这个的下面才是显示的内容

??? String editUrl; //编辑页面的URL

??? String delUrl; //删除页面的URL

??? String viewUrl; //查看指定记录URL

??? String currentPageUrl;

??? boolean verify = false; //是否当前记录验证

??? String verifyURL; //记录的验证地址

?

??? /******************************初使化数据库链接******************************/

??? private void conn_init() {

??????? setConnection();

??????? setStatement();

??? }

?

??? private void setConnection() {

??????? try {

????????? ??Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

??????????? String strurl;

??????????? strurl =

??????????????????? "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=D://Palfinger//palfinger.mdb";

??????????? conn = DriverManager.getConnection(strurl);

??????? } catch (Exception e) {

??????????? e.printStackTrace();

??????? }

??? }

?

??? private void setStatement() {

??????? try {

??????????? st =

?conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

??????? } catch (SQLException e) {

??????????? e.printStackTrace();

??????? }

??? }

??? /*****************************初使化数据库链接OK*****************************/

?

??? /**

???? *

???? * @param sql 执行的SQL语句

???? * @param CurrentPage 当前页

???? * @param PageSize 每页显示的记录数

???? * @return 执行的结果到StringBuffer

???? */

??? public StringBuffer getResult_withTableFormat(String sql, int CurrentPage,

????????????????????????????????????????????????? int PageSize,

????????????????????????????????????????????????? boolean withEdit) {

?????? ?int rowNum = 0; //总行数

??????? int TotalPage = 0; //总页数

??????? int beginRow = 0; //起始记录

??????? int endRow = 0; //结束记录

??????? StringBuffer resultRows = new StringBuffer(""); //结果集

??????? this.pageSize = PageSize; //每页大小

??????? try {

??????????? rowNum = getTotalResultSetNum(sql); //取得总记录数

??????????? this.totalRecord = rowNum; //总记录数

??????????? //确定当前页

??????????? if (rowNum % PageSize == 0) {

??????????????? TotalPage = rowNum / PageSize;

??????????? } else

??????????????? TotalPage = rowNum / PageSize + 1;

??????????? if (CurrentPage >= TotalPage) {

??????????????? CurrentPage = TotalPage;

??????????????? nextPage = CurrentPage;

??????????????? nextPage = CurrentPage + 1; //得到下一页页号

??????????? } else {

??????????????? nextPage = CurrentPage + 1; //得到下一页页号

??????????? }

?

??????????? if (CurrentPage <= 1) {

??????????????? CurrentPage = 1;

??????????????? previousPage = CurrentPage; //得到前一页页号

??????????? } else {

??????????????? previousPage = CurrentPage - 1; //得到前一页页号

??????????? }

??????????? this.currentPage = CurrentPage; //设置当前页

??????????? this.totalPage = TotalPage; //设置总页数

??????????? beginRow = (CurrentPage - 1) * PageSize + 1; //开始记录

??????????? endRow = beginRow + PageSize; //结束记录

??????????? resultRows =

??????????????????? getExecuteResult_withTableFormat(sql, beginRow, endRow,

???????????????????????????????????????????????????? withEdit);

??????? } catch (Exception e) {

??????????? e.printStackTrace();

??????? }

??????? return resultRows;

??? }

?

??? /**

???? *

???? * @param sql 要执行的SQL语句

???? * @param startPos 记录的开始点,即从得到结果的第几条记录开始返回

???? * @param endPos 返回记录的结束点,即最后一条记录

???? * @param withEdit 是否加上编辑链接

???? * @return 根据SQL语句生成的放在BufferString,并返回

???? */

??? private StringBuffer getExecuteResult_withTableFormat(String sql,

??????????????? ?????????????????????????????????????????int startPos,

???????????????????????????????????????????????????????? int endPos,

???????????????????????????????????????????????????????? boolean withEdit) {

??????? ResultSet rs;

??????? ResultSetMetaData rsmd; //取得元数据

??????? int ColumnCount; //返回结果有多少列

??????? StringBuffer resultStr = new StringBuffer("");

??????? resultStr.append("<table border=1>");

??????? try {

??????????? rs = st.executeQuery(sql);

??????????? rsmd = rs.getMetaData();

??????????? ColumnCount = rsmd.getColumnCount();

??????????? this.columnCount = ColumnCount;

??????????? resultStr.append("<tr>");

??????????? resultStr.append("<td colspan=" + (columnCount + 2) + " align=center>");

??????????? resultStr.append("<font size=6>" + getTableTitle() + "</font>");

??????????? resultStr.append("</td>");

??????????? resultStr.append("</tr>");

??????????? //System.out.println("ColumnCount:" + ColumnCount);

??????????? //System.exit(0);

??????????? //取得列名,列名的顺序下标是从1开始的

??????????? resultStr.append("<tr>");

??????????? for (int j = 1; j <= ColumnCount; j++) {

??????????????? resultStr.append("<td align=left>&nbsp;");

??????????????? //这个方法,可以将英文字段替换为中文

??????????????? //resultStr.append(replaceEnglishHeadWithChinese(rsmd.getColumnName(j)));

??????????????? resultStr.append(rsmd.getColumnName(j));

??????????????? resultStr.append("</td>");

??????????? }

??????????? resultStr.append("<td>");

??????????? resultStr.append("</td>");

??????????? if (withEdit == true) {

??????????????? resultStr.append("<td>");

??????????????? resultStr.append("<b>? </b>");

??????????????? resultStr.append("</td>");

??????????? }

??????????? resultStr.append("</tr>");

??????????? int currentRecordNum = (currentPage - 1) * 20 + 1;

??????????? ;

??????????? if (rs.next()) {

??????????????? rs.absolute(startPos); //记录绝对定位

??????????????? for (int i = 0; i < (endPos - startPos); i++) {

??????????????????? resultStr.append("<tr>");

??????????????????? int componentID = 0; //这个范指所有的表中的ID字段

??????????????????? for (int j = 1; j <= ColumnCount; j++) {

???????????????????? ???if (j == 1) {

??????????????????????????? {

??????????????????????????????? resultStr.append("<td align=left>&nbsp;");

??????????????????????????????? //resultStr.append(rs.getInt(j));

??????????????????????????????? resultStr.append(currentRecordNum++); //不用数据库的ID,自已经生成ID

??????????????????????????????? resultStr.append("</td>");

??????????????????????????????? componentID = rs.getInt(j);

??????????????????????????? }

??????????????????????? } else {

??????????????????????????? resultStr.append("<td align=left>&nbsp;");

??????????????????????????? resultStr.append(rs.getString(j));

??????????????????????????? resultStr.append("</td>");

??????????????????????? }

??????????????????? }

??????????????????? resultStr.append("<td>");

??????????????????? resultStr.append("<a href=" + getViewUrl() + "?id=" +

???????????????????????????????????? componentID +

???????????????????????????????????? " target=_blank><font color=green><nobr>查看</nobr></font></a>");

??????????????????? resultStr.append("</td>");

?????????? ?????????if (withEdit == true) {

??????????????????????? resultStr.append("<td>");

??????????????????????? resultStr.append("<nobr>");

?

??????????????????????? resultStr.append("<a href=" + getEditUrl() + "?id=" +

???????????????????????????????????????? componentID +

???????????????????????????????????????? "><font color=blue>编辑</font></a>");

??????????????????????? resultStr.append("&nbsp;&nbsp;");

?

??????????????????????? resultStr.append("<a href=# onclick=delSure(''" +

?????????????????????????????? ??????????getDelUrl() + "id=" + componentID +

???????????????????????????????????????? "'')><font color=red>删除</font></a>");

??????????????????????? if (isVerify() == true) {

??????????????????????????? resultStr.append("&nbsp;&nbsp;");

?????????????????? ?????????resultStr.append("<a href=# onclick=passSure(''" +

???????????????????????????????????????????? getVerifyURL() + "?id=" +

???????????????????????????????????????????? componentID +

???????????????????????????????????????????? "'')><font color=red>审核</font></a>");

??????????????????????? }

??????????????????????? resultStr.append("</nobr>");

??????????????????????? resultStr.append("</td>");

??????????????????? }

??????????????????? resultStr.append("</tr>");

??????????????????? rs.next();

??????? ????????????if (rs.isAfterLast()) {

??????????????????????? break;

??????????????????? }

??????????????? }

??????????? }

??????????? resultStr.append("<tr>");

??????????? resultStr.append("<td colspan=" + (ColumnCount + 2) +

???????????????????????????? " align=center>");

??????????? resultStr.append(setTurnPageString(getCurrentPageUrl()));

??????????? resultStr.append("</td>");

??????????? resultStr.append("</tr>");

??????????? resultStr.append("</table>");

??????? } catch (SQLException e) {

??????????? e.printStackTrace();

??????? }

??????? return resultStr;

??? }

?

??? /**

???? *

???? * @param httpUrl URL地址,可以是带参数的

???? * @return 生成的首页、上页、下页、末页等字符串

???? */

??? private String setTurnPageString(String httpUrl) {

??????? String turnPageStrng = "";

??????? String divideS = "&nbsp;&nbsp;&nbsp;&nbsp;";

??????? turnPageStrng = "总记录数:" + totalRecord;

??????? turnPageStrng = turnPageStrng + divideS + "总页数:" + totalPage;

??????? turnPageStrng = turnPageStrng + divideS + "每页记录数:" + pageSize;

??????? if (httpUrl.indexOf("?") > 0) //如果请求地址是有条件的,就加&连接其它的条件

??????????? httpUrl += "&page=";

??????? else

??????????? httpUrl += "?page=";

??????? String hS = "<a href=" + httpUrl + "1>首页</a>" + divideS;

??????? String pS = "<a href=" + httpUrl + previousPage + ">前页</a>" + divideS;

??????? String cS = "当前第" + currentPage + "" + divideS;

??????? String tS = "转到第<input type=text size=2 id=goToPage";

??????? tS += " onKeyDown=/"if(window.event.keyCode==13) goToPage(''";

??????? tS += httpUrl + "'');/" value=" + nextPage + ">";

??? ????tS += "<input type=button name=g value=Go ";

??????? tS += "onclick=/"goToPage(''" + httpUrl + "'');/">" + divideS;

??????? String nS = "<a href=" + httpUrl + nextPage + ">下页</a>" + divideS;

??????? String lS = "<a href=" + httpUrl + totalPage + ">末页</a>";

??????? turnPageStrng = turnPageStrng + divideS + hS + pS + cS + tS + nS + lS;

??????? return turnPageStrng;

??? }

?

??? /**

???? * 取得总记录数

???? * @return

???? */

??? private int getTotalResultSetNum(String sql) {

??????? int num = 0;

??????? ResultSet rs;

??????? try {

??????????? rs = st.executeQuery(sql);

??????????? if (rs.next()) {

??????????????? rs.last(); //移到最后一条

??????????????? num = rs.getRow(); //取得总记录数

??????????????? rs.first(); //再移到第一条记录

??????????? }

??????? } catch (SQLException e) {

???? ???????e.printStackTrace();

??????? }

??????? return num;

??? }

?

??? /**************************针对变量的setget方法**************************/

??? public

??? //设置表头

??? void setTableTitle(String tableTitle) {

??????? this.tableTitle = tableTitle;

??? }

??? //取得表头

?

??? private String getTableTitle() {

??????? return tableTitle;

??? }

??? //设置查看对应记录的URL

?

??? public void setViewUrl(String viewUrl) {

??????? this.viewUrl = viewUrl;

??? }

??? //取得查看对应记录的URL

?

??? private String getViewUrl() {

??????? return viewUrl;

?? ?}

??? //设置编辑指定记录的URL

?

??? public void setEditUrl(String editUrl) {

??????? this.editUrl = editUrl;

??? }

??? //取得编辑指定记录的URL

?

??? private String getEditUrl() {

??????? return editUrl;

??? }

??? //设置删除指定记录的URL

?

??? public void setDelUrl(String delUrl) {

??? ????this.delUrl = delUrl;

??? }

??? //取得删除指定记录的URL

?

??? private String getDelUrl() {

??????? return delUrl;

??? }

??? //设置是否通过验证

?

??? public void setVerify(boolean verify) {

??????? this.verify = verify;

??? }

??? //获得是否通过验证

?

??? private boolean isVerify() {

??????? return verify;

??? }

??? //设置通过验证指定记录的URL

?

??? public void setVerifyURL(String verifyURL) {

??????? this.verifyURL = verifyURL;

??? }

??? //取得验证指定记录的URL

?

??? private String getVerifyURL() {

??????? return verifyURL;

??? }

??? //设置当前页的URL

?

??? public void setCurrentPageUrl(String currentPageUrl) {

??????? this.currentPageUrl = currentPageUrl;

??? }

??? //取得当前页的URL

?

??? private String getCurrentPageUrl() {

??????? return currentPageUrl;

??? }

??? /**************************针对变量的setget方法OK**************************/

}

?

/*

附:

??? 1、将英文字段替换为中文字段的函数:

??? String replaceEnglishHeadWithChinese(String etitle) {

??????? String ctitle = "";

??????? if (etitle.trim().toLowerCase().equals("id"))

??????????? ctitle = "<b>序号</b>";

??????? if (etitle.trim().equals("serialnumber"))

??????????? ctitle = "<b>物料编号</b>";

?????? ? ...

???????????

??????? if(ctitle=="") {

??????????? ctitle="<b>"+etitle+"</b>";

??????? }

??????? return ctitle;

?}

2、执行在框中输入翻页的JS函数:

//转到第几页

??? function goToPage(httpUrl)

??? {

??????? var page=document.getElementById("goToPage").value;

??????? var url=httpUrl+page;

??????? window.location=url;

}

*/

  相关解决方案