【util】工具类方法 总结

utils.js:可供其他页面共享的js

1.将点击事件抽象到utils.js中

                   ·这种方法写完之后能够保证js的优美,当页面有多个click事件时能够避免代码重复,并且将click事件集中到一起

utils.js

/**
 * Created by 111 on 2016/3/10.
 */
var utils = {};
utils.quick ={
    click:function(method,node){
        var list = null;
        if(node){
            list = $(node).find("[data-click]");
        }else{
            list = $("[data-click]");
        }
        list.on("click",function(eventObject){
//this指当前对象,若为save,则this指<button id="goHome" data-click="save">data测试save</button>
            var click =$(this).data("click");
            if(click && method[click]){        //获取button的附加click元素
                return method[click].apply(this,[eventObject]);
            }
        });
    },
    offClick:function(node){
        if(node){
            $(node).find("[data-click]").off('click');
        }else{
            $("[data-click]").off('click');
        }
    }
};



      ·使用data-click属性来自定义点击方法名

页面

<%@ page isELIgnored="false"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <link rel="stylesheet" href="${resource}/css/index.css?revision=${revision}">
    <title></title>
    <script type="text/javascript" src="${resource}/lib/jquery/jquery-2.1.3.min.js"></script>
    <script type="text/javascript" src="${resource}/js/utils.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            utils.quick.click({
                save:function(){
                    utils.quick.offClick("#save");//取消绑定点击事件,第二次点击不会相应
                    alert("save");
                }
            },"#save")//只有id为save的标签内的含有data-click属性的标签会被查找出来,绑定点击事件,
                          //如果省略则所有的具有data-click属性的元素都会查找出来然后判断
        })
    </script>
</head>
<body>
<div id="save">
    <button id="goHome" data-click="save">data测试save</button>
</div>
<button id="go" data-click="query">data测试query</button>

</body>
</html>


多个data-click 属性可以这样写:

 $(document).ready(function(){
            utils.quick.click({
                save:function(){
                    alert("save");
                },
                query:function(){
                    alert("query");
                }
            });
        });

2.生成全局唯一标识符(UUID):通常可作为一个id使用,基本不会重复


utils.uuid= {
    uuid:function(){
        var d = new Date().getTime();
        var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){
            var r = (d+Math.random()*16)%16 |0;    // Math.random()*16 随机产生0-16之间的小数 % 模运算即取余
            d = Math.floor(d/16);                 //round()四舍五入;floor()向上取整;ceil()向下取整;
            return (c = 'x'?r:(r &0x7 |0x8)).toString(16);
        });
        return uuid;
    }
};

js调用

alert(utils.uuid.uuid());

3.js模板引擎nano的使用:就不需要再去拼html了

utils.template = {
    // JS模板工具 https://github.com/trix/nano
    /**
     * @param template  静态的模板,模型使用{object.name}的形式
     * @param data      填充的数据对象
     * @returns {XML|string|void}
     */
    nano: function (template, data) {
        return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
            var keys = key.split("."), v = data[keys.shift()];
            for (var i = 0, l = keys.length; i < l; i++) v = v[keys[i]];
            return (typeof v !== "undefined" && v !== null) ? v : "";
        });
    }
};


        ·语法:

utils.template.nano(template,data);//template指填充数据的模板,可以为静态模板,写在页面上,data指用来填充的数据


简单使用

<!--jsp1.2默认不使用el表达式,如果遇到el表达式没解析,可以试试加上这个-->
<%@ page isELIgnored="false"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <link rel="stylesheet" href="${resource}/css/index.css?revision=${revision}">
    <title></title>
    <script type="text/javascript" src="${resource}/lib/jquery/jquery-2.1.3.min.js"></script>
    <script type="text/javascript" src="${resource}/js/utils.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            var data = {              //模拟填充的数据
                user: {
                    login: "tomek",
                    first_name: "Thomas",
                    last_name: "Mazur",
                    account: {
                        status: "active",
                        expires_at: "2009-12-31"
                    }
                }
            }
            var item = utils.template.nano($("#templateTest").html(),data);
            $("#nano-test").html(item);
//            $("#nano-test").html(utils.template.nano("<p>Hello {user.first_name} {user.last_name}! Your account is <strong>{user.account.status}</strong></p>", data));
        })
    </script>
</head>
<body>
<div id="nano-test"></div>
//静态模板,或者不使用直接用js中注释的方法插入
<script type="text/html" id="templateTest">
    <p>Hello {user.first_name} {user.last_name}! Your account is <strong>{user.account.status}</strong></p>
</script>
</body>
</html>

异步请求list数据,不分页

<%--
  Created by IntelliJ IDEA.
  User: 111
  Date: 2016/2/10
  Time: 11:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCtype html>
<html>
<head>
    <%--<script type="text/javascript" src="../public/js/amd_test.js"></script>--%>
    <script type="text/javascript" src="../public/js/utils.js"></script>
    <script type="text/javascript" src="../public/lib/jquery/jquery-2.1.3.min.js"></script>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
            $.ajax({                 //请求到list数据,list保存的对象含有name和sex字段
                url:'../test/data',
                dataType:'json',
                method:'post',
                async:false,
                success:function(data){
                    $.each(data,function(index,item){
                        $("#tbody").append(utils.template.nano($("#template-list").html(),item));
                    })
                },
                error:function(XMLHttpRequest ,textStatus,errorThrown){
                    console.log(XMLHttpRequest.status+"/n"+XMLHttpRequest.statusText+"/n"+errorThrown+"/n");
                }
            })
        }
    </script>
</head>
<body>
<div>
    <table>
        <thead>
        <tr>
            <th>姓名</th>
            <th>性别</th>
        </tr>
        </thead>
        <tbody id="tbody"></tbody>
    </table>
</div>
<script type="text/html" id="template-list">
  <tr>
      <td>{name}</td>
      <td>{sex}</td>
  </tr>
</script>
</body>
</html>

分页的后期根据前端分页插件提供



4.美化页面的弹出框和确定框(需要bootstrap插件 ,需要上面的nano js引擎,uuid)

     ·alert/confirm  utils.js

utils.modal = {
        /**
         * myAlert
         * @param title 标题 不填则默认
         * @param body 内容
         * @param callback 回调函数
         */
        myAlert: function () {
            var settings = resolveModal.apply({}, arguments);
            myAlert.open(settings);
        },
    /**
     * myConfirm
     * @param title 标题
     * @param body 内容
     * @param callback 回调函数
     */
    myConfirm: function () {
        var settings = resolveModal.apply({}, arguments);
        myConfirm.open(settings);
    }
};
var resolveModal = function () {//解析调用时的参数,并返回
    var settings = null;
    if (arguments.length == 1) {//仅一个参数
        if ($.type(arguments[0]) == 'string') {
            settings = {
                body: arguments[0]
            }
        } else if ($.type(arguments[0]) == 'object') {
            settings = arguments[0];
        } else if ($.type(arguments[0]) == 'function') {
            settings = {
                callback: arguments[0]
            }
        }
    } else if (arguments.length == 2) {//两个参数
        if ($.type(arguments[1]) == 'function') {
            settings = {
                body: arguments[0],
                callback: arguments[1]
            }
        } else {
            settings = {
                title: arguments[0],
                body: arguments[1]
            }
        }
    } else if (arguments.length == 3) {//三个参数
        settings = {
            title: arguments[0],
            body: arguments[1],
            callback: arguments[2]
        }
    }
    return settings;
};
var myAlert = {
    id: null,
    template: '<div class="modal fade" id="{id}" style="width: 360px" role="dialog" aria-hidden="true"><div class="modal-dialog" style="width: 360px;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title"></h4></div><div class="modal-body" style="font-size:16px;"></div><div class="modal-footer"><button type="button" class="btn btn-primary">确定</button></div></div></div></div>',
    settings: {
        title: '消息提示',
        body: '消息提示'
    },
    init: function () {
        $('#' + this.id).on('hide.bs.modal', function () {
            myAlert.callback();
        });
        this.init = null;
    },
    callback: $.noop,
    close: function () {
        $('#' + myAlert.id).modal('hide');
    },
    open: function (options) {
        if (!this.id) {
            this.id = utils.uuid.uuid();
            $('body').append(utils.template.nano(this.template, {id: this.id}));
            $('#' + this.id + ' button.btn-primary').on('click', myAlert.close);
        }
        var dom = $('#' + this.id), setting = $.extend({}, this.settings, options);
        this.callback = setting.callback ? setting.callback : $.noop;
        $('h4.modal-title', dom).text(setting.title);
        $('div.modal-body', dom).html(setting.body);
        document.activeElement && $(document.activeElement).blur();
        dom.modal({backdrop: 'static', show: true});
        this.init && this.init();
    }
}
var myConfirm = {
    id: null,
    template: '<div class="modal fade" id="{id}" role="dialog" aria-hidden="true" style="width: 360px"><div class="modal-dialog" style="width: 360px;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title"></h4></div><div class="modal-body" style="font-size:16px;"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-primary">确定</button></div></div></div></div>',
    settings: {
        title: '消息提示',
        body: '确定继续'
    },
    callback: $.noop,
    result: false,
    init: function () {
        $('#' + this.id).on('hide.bs.modal', function () {
            myConfirm.callback(myConfirm.result);
        });
        this.init = null;
    },
    close: function () {
        $('#' + myConfirm.id).modal('hide');
    },
    open: function (options) {
        if (!this.id) {
            this.id = utils.uuid.uuid();
            $('body').append(utils.template.nano(this.template, {id: this.id}));
            $('#' + this.id + ' button.btn-primary').on('click', function () {
                myConfirm.result = true;
                myConfirm.close();
            });
        }
        var dom = $('#' + this.id), setting = $.extend({}, this.settings, options);
        $('h4.modal-title', dom).text(setting.title);
        $('div.modal-body', dom).html(setting.body);
        this.callback = setting.callback ? setting.callback : $.noop;
        this.result = false;
        document.activeElement && $(document.activeElement).blur();
        dom.modal({backdrop: 'static', show: true});
        this.init && this.init();
    }
}



测试页面

        window.onload = function(){
            utils.modal.myAlert("提示","操作失败!",function(){
                    alert("111");
            });
            utils.modal.myConfirm("提示","确定删除吗",function(flag){
                    alert(flag);
            });
        };


整体代码,可直接复制使用,css 需要的可以微调

var utils = {};

utils.uuid= {
    uuid:function(){
        var d = new Date().getTime();
        var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(c){
            var r = (d+Math.random()*16)%16 |0;    // Math.random()*16 随机产生0-16之间的小数 % 模运算即取余
            d = Math.floor(d/16);                 //round()四舍五入;floor()向上取整;ceil()向下取整;
            return (c = 'x'?r:(r &0x7 |0x8)).toString(16);
        });
        return uuid;
    }
};
utils.modal = {
    /**
     * myAlert
     * @param title 标题 不填则默认
     * @param body 内容
     * @param callback 回调函数
     */
    myAlert: function () {
        var settings = resolveModal.apply({}, arguments);
        myAlert.open(settings);
    },
    /**
     * myConfirm
     * @param title 标题
     * @param body 内容
     * @param callback 回调函数
     */
    myConfirm: function () {
        var settings = resolveModal.apply({}, arguments);
        myConfirm.open(settings);
    }
};
var resolveModal = function () {//解析调用时的参数,并返回
    var settings = null;
    if (arguments.length == 1) {//仅一个参数
        if ($.type(arguments[0]) == 'string') {
            settings = {
                body: arguments[0]
            }
        } else if ($.type(arguments[0]) == 'object') {
            settings = arguments[0];
        } else if ($.type(arguments[0]) == 'function') {
            settings = {
                callback: arguments[0]
            }
        }
    } else if (arguments.length == 2) {//两个参数
        if ($.type(arguments[1]) == 'function') {
            settings = {
                body: arguments[0],
                callback: arguments[1]
            }
        } else {
            settings = {
                title: arguments[0],
                body: arguments[1]
            }
        }
    } else if (arguments.length == 3) {//三个参数
        settings = {
            title: arguments[0],
            body: arguments[1],
            callback: arguments[2]
        }
    }
    return settings;
};
var myAlert = {
    id: null,
    template: '<div class="modal fade" id="{id}" role="dialog" aria-hidden="true"><div class="modal-dialog" style="width: 360px;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title"></h4></div><div class="modal-body" style="font-size:16px;"></div><div class="modal-footer"><button type="button" class="btn btn-primary">确定</button></div></div></div></div>',
    settings: {
        title: '消息提示',
        body: '消息提示'
    },
    init: function () {
        $('#' + this.id).on('hide.bs.modal', function () {
            myAlert.callback();
        });
        this.init = null;
    },
    callback: $.noop,
    close: function () {
        $('#' + myAlert.id).modal('hide');
    },
    open: function (options) {
        if (!this.id) {
            this.id = utils.uuid.uuid();
            $('body').append(utils.template.nano(this.template, {id: this.id}));
            $('#' + this.id + ' button.btn-primary').on('click', myAlert.close);
        }
        var dom = $('#' + this.id), setting = $.extend({}, this.settings, options);
        this.callback = setting.callback ? setting.callback : $.noop;
        $('h4.modal-title', dom).text(setting.title);
        $('div.modal-body', dom).html(setting.body);
        document.activeElement && $(document.activeElement).blur();
        dom.modal({backdrop: 'static', show: true});
        this.init && this.init();
    }
}
var myConfirm = {
    id: null,
    template: '<div class="modal fade" id="{id}" role="dialog" aria-hidden="true"><div class="modal-dialog" style="width: 360px;"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4 class="modal-title"></h4></div><div class="modal-body" style="font-size:16px;"></div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">取消</button><button type="button" class="btn btn-primary">确定</button></div></div></div></div>',
    settings: {
        title: '消息提示',
        body: '确定继续'
    },
    callback: $.noop,
    result: false,
    init: function () {
        $('#' + this.id).on('hide.bs.modal', function () {
            myConfirm.callback(myConfirm.result);
        });
        this.init = null;
    },
    close: function () {
        $('#' + myConfirm.id).modal('hide');
    },
    open: function (options) {
        if (!this.id) {
            this.id = utils.uuid.uuid();
            $('body').append(utils.template.nano(this.template, {id: this.id}));
            $('#' + this.id + ' button.btn-primary').on('click', function () {
                myConfirm.result = true;
                myConfirm.close();
            });
        }
        var dom = $('#' + this.id), setting = $.extend({}, this.settings, options);
        $('h4.modal-title', dom).text(setting.title);
        $('div.modal-body', dom).html(setting.body);
        this.callback = setting.callback ? setting.callback : $.noop;
        this.result = false;
        document.activeElement && $(document.activeElement).blur();
        dom.modal({backdrop: 'static', show: true});
        this.init && this.init();
    }
}
utils.template = {
    // JS模板工具 https://github.com/trix/nano
    /**
     * @param template  静态的模板,模型使用{object.name}的形式
     * @param data      填充的数据对象
     * @returns {XML|string|void}
     */
    nano: function (template, data) {
        return template.replace(/\{([\w\.]*)\}/g, function (str, key) {
            var keys = key.split("."), v = data[keys.shift()];
            for (var i = 0, l = keys.length; i < l; i++) v = v[keys[i]];
            return (typeof v !== "undefined" && v !== null) ? v : "";
        });
    }
};


5.简单的判别浏览器(ie/firefox/chrome,新出的win10的edge浏览器在这里匹配不成功,显示的是chrome浏览器,需要的话需要重写)

     edge的navigator.userAgent:mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/46.0.2486.0 safari/537.36 edge/13.10586

utils.browser ={
        isIE: function () {
            return /msie/.test(navigator.userAgent.toLowerCase()) || /rv:([\d.]+)\) like gecko/.test(navigator.userAgent.toLowerCase());
        },
        isFirefox: function () {
            return /firefox/.test(navigator.userAgent.toLowerCase());
        },
        isChrome: function () {
            return /chrome/.test(navigator.userAgent.toLowerCase());
        },
        get: function () {
            var browser = {};
            var ua = navigator.userAgent.toLowerCase();
            var s;
            (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? browser.ie = s[1] : (s = ua.match(/msie ([\d.]+)/)) ? browser.ie = s[1] : (s = ua.match(/firefox\/([\d.]+)/)) ? browser.firefox = s[1] : (s = ua.match(/chrome\/([\d.]+)/)) ? browser.chrome = s[1] : (s = ua.match(/opera.([\d.]+)/)) ? browser.opera = s[1] : (s = ua.match(/version\/([\d.]+).*safari/)) ? browser.safari = s[1] : 0;
            return browser;
        }
}

6.订阅/发布/取消订阅模式(观察者模式)


jquery版

(function ($) {  //jquery私有作用域
    var o = $({});
    $.subscribe = function () {
        o.on.apply(o, arguments);
    };
    $.unsubscribe = function () {
        o.off.apply(o, arguments);
    };
    $.publish = function () {
        o.trigger.apply(o, arguments);
    };
}(jQuery));

页面调用

      ·订阅一个事件,函数中执行代码,接下来如果想调用这个事件,则直接发布即可,如果想取消这个订阅事件,则取消即可。

<%--
  Created by IntelliJ IDEA.
  User: 111
  Date: 2016/2/10
  Time: 11:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCtype html>
<html>
<head>
    <%--<script type="text/javascript" src="../public/js/amd_test.js"></script>--%>
        <link rel="stylesheet" href="../public/lib/bootstrap/css/bootstrap.min.css">
        <script type="text/javascript" src="../public/lib/jquery/jquery-2.1.3.min.js"></script>
        <script type="text/javascript" src="../public/js/utils.js"></script>
        <script type="text/javascript" src="../public/lib//bootstrap/js/bootstrap.min.js"></script>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
            utils.quick.click({
                btn:function(){
                    $.publish("/test/data");
                    $.unsubscribe("");
                }
            })
            $.subscribe("/test/data",function(){
                alert("subscribe");
            });
        };
    </script>
</head>
<body>
<div>
    <button data-click="btn">点击</button>
</div>
</body>
</html>

7.对字符串判断的一些util类

utils.string = {
    trim: function (str) {
        return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, '');
    },
    isEmpty: function (str) {
        return (!str || 0 === str.length);
    },
    isNotEmpty: function (str) {
        return !this.isEmpty(str);
    },
    isBlank: function (str) {
        return (!str || 0 === this.trim(str).length);
    },
    isNotBlank: function (str) {
        return !this.isBlank(str);
    },
    startwith:function(data,str){
        if(str==null||str==""||data == null ||data.length==0||str.length>data.length)
            return false;
        if(data.substr(0,str.length)==str)
            return true;
        else
            return false;
        return true;

    },
    endwith:function(data,str){
        if(str==null||str==""||data == null ||data.length==0||str.length>data.length)
            return false;
        if(data.substring(data.length-str.length)==str)
            return true;
        else
            return false;
        return true;
    }
};

8.ajax的get/post请求

utils.js

utils.myAjax ={
        post: function () {
            var list = resolveAjax(arguments);
            var settings = {
                url:  list[0],
                dataType: 'json',
                type: 'POST',
                data: list[1],
                cache: false
            };
            $.ajax(settings).done(list[2]).fail(function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.status == 200 && XMLHttpRequest.responseText.indexOf('<title>CAS – Central Authentication Service</title>') > 0) {
                    utils.modal.alert('登录超时', function () {
                        location.reload();
                    });
                } else {
                    list[3](XMLHttpRequest, textStatus, errorThrown)
                }
            });
        },
        get: function () {
            var list = resolveAjax(arguments);
            var settings = {
                url: list[0],
                dataType: 'json',
                type: 'GET',
                data: list[1],
                cache: false
            };
            $.ajax(settings).done(list[2]).fail(function (XMLHttpRequest, textStatus, errorThrown) {
                if (XMLHttpRequest.status == 401) {
                    location.reload();
                }
                else {
                    list[3](XMLHttpRequest, textStatus, errorThrown)
                }
            });
        }
};
var resolveAjax = function (arg) {
    if (!arg.length) {
        throw 'URL不能为空'
    }
    var result = [];
    for (var i = 0; i < arg.length; i++) {
        result.push(arg[i]);
    }
    if ($.type(result[1]) == 'function') {
        result.splice(1, 0, '');
    }
    if (!result[3]) {
        result.push($.noop);
    }
    return result;
};

页面调用:

      utils.myAjax.post("../test/data",{},function(){
                alert("11");
            });




package com.hexiang.utils; import java.sql.*; import java.util.*; /** * * Title: 数据库工具类 * * * Description: 将大部分的数据库操作放入这个类中, 包括数据库连接的建立, 自动释放等. * * * @author beansoft 日期: 2004年04月 * @version 2.0 */ public class DatabaseUtil { /** 数据库连接 */ private java.sql.Connection connection; /** * All database resources created by this class, should be free after all * operations, holds: ResultSet, Statement, PreparedStatement, etc. */ private ArrayList resourcesList = new ArrayList(5); public DatabaseUtil() { } /** 关闭数据库连接并释放所有数据库资源 */ public void close() { closeAllResources(); close(getConnection()); } /** * Close given connection. * * @param connection * Connection */ public static void close(Connection connection) { try { connection.close(); } catch (Exception ex) { System.err.println("Exception when close a connection: " + ex.getMessage()); } } /** * Close all resources created by this class. */ public void closeAllResources() { for (int i = 0; i < this.getResourcesList().size(); i++) { closeJDBCResource(getResourcesList().get(i)); } } /** * Close a jdbc resource, such as ResultSet, Statement, Connection.... All * these objects must have a method signature is void close(). * * @param resource - * jdbc resouce to close */ public void closeJDBCResource(Object resource) { try { Class clazz = resource.getClass(); java.lang.reflect.Method method = clazz.getMethod("close", null); method.invoke(resource, null); } catch (Exception e) { // e.printStackTrace(); } } /** * 执行 SELECT 等 SQL 语句并返回结果集. * * @param sql * 需要发送到数据库 SQL 语句 * @return a ResultSet object that contains the data produced * by the given query; never null */ public ResultSet executeQuery(String sql) { try { Statement statement = getStatement(); ResultSet rs = statement.executeQuery(sql); this.getResourcesList().add(rs); this.getResourcesList().add(statement);// BUG fix at 2006-04-29 by BeanSoft, added this to res list // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); return rs; } catch (Exception ex) { System.out.println("Error in executeQuery(\"" + sql + "\"):" + ex); // ex.printStackTrace(); return null; } } /** * Executes the given SQL statement, which may be an INSERT, * UPDATE, or DELETE statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE 语句, 或者是一个不返回任何东西的 SQL 语句, 例如一个 SQL * DDL 语句. * * @param sql * an SQL INSERT,UPDATE or * DELETE statement or an SQL statement that * returns nothing * @return either the row count for INSERT, * UPDATE or DELETE statements, or * 0 for SQL statements that return nothing */ public int executeUpdate(String sql) { try { Statement statement = getStatement(); return statement.executeUpdate(sql); // MySql 数据库要求必需关闭 statement 对象, 否则释放不掉资源 // - 此观点错误, 因为关闭此对象后有时数据无法读出 //statement.close(); } catch (Exception ex) { System.out.println("Error in executeUpdate(): " + sql + " " + ex); //System.out.println("executeUpdate:" + sql); ex.printStackTrace(); } return -1; } /** * 返回记录总数, 使用方法: getAllCount("SELECT count(ID) from tableName") 2004-06-09 * 可滚动的 Statement 不能执行 SELECT MAX(ID) 之类的查询语句(SQLServer 2000) * * @param sql * 需要执行的 SQL * @return 记录总数 */ public int getAllCount(String sql) { try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); ResultSet rs = statement.executeQuery(sql); rs.next(); int cnt = rs.getInt(1); rs.close(); try { statement.close(); this.getResourcesList().remove(statement); } catch (Exception ex) { ex.printStackTrace(); } return cnt; } catch (Exception ex) { System.out.println("Exception in DatabaseUtil.getAllCount(" + sql + "):" + ex); ex.printStackTrace(); return 0; } } /** * 返回当前数据库连接. */ public java.sql.Connection getConnection() { return connection; } /** * 连接新的数据库对象到这个工具类, 首先尝试关闭老连接. */ public void setConnection(java.sql.Connection connection) { if (this.connection != null) { try { getConnection().close(); } catch (Exception ex) { } } this.connection = connection; } /** * Create a common statement from the database connection and return it. * * @return Statement */ public Statement getStatement() { // 首先尝试获取可滚动的 Statement, 然后才是普通 Statement Statement updatableStmt = getUpdatableStatement(); if (updatableStmt != null) return updatableStmt; try { Statement statement = getConnection().createStatement(); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getStatement(): " + ex); } return null; } /** * Create a updatable and scrollable statement from the database connection * and return it. * * @return Statement */ public Statement getUpdatableStatement() { try { Statement statement = getConnection() .createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(statement); return statement; } catch (Exception ex) { System.out.println("Error in getUpdatableStatement(): " + ex); } return null; } /** * Create a prepared statement and return it. * * @param sql * String SQL to prepare * @throws SQLException * any database exception * @return PreparedStatement the prepared statement */ public PreparedStatement getPreparedStatement(String sql) throws SQLException { try { PreparedStatement preparedStatement = getConnection() .prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); this.getResourcesList().add(preparedStatement); return preparedStatement; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Return the resources list of this class. * * @return ArrayList the resources list */ public ArrayList getResourcesList() { return resourcesList; } /** * Fetch a string from the result set, and avoid return a null string. * * @param rs * the ResultSet * @param columnName * the column name * @return the fetched string */ public static String getString(ResultSet rs, String columnName) { try { String result = rs.getString(columnName); if (result == null) { result = ""; } return result; } catch (Exception ex) { } return ""; } /** * Get all the column labels * * @param resultSet * ResultSet * @return String[] */ public static String[] getColumns(ResultSet resultSet) { if (resultSet == null) { return null; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); if (numberOfColumns <= 0) { return null; } String[] columns = new String[numberOfColumns]; //System.err.println("numberOfColumns=" + numberOfColumns); // Get the column names for (int column = 0; column < numberOfColumns; column++) { // System.out.print(metaData.getColumnLabel(column + 1) + "\t"); columns[column] = metaData.getColumnName(column + 1); } return columns; } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Get the row count of the result set. * * @param resultset * ResultSet * @throws SQLException * if a database access error occurs or the result set type is * TYPE_FORWARD_ONLY * @return int the row count * @since 1.2 */ public static int getRowCount(ResultSet resultset) throws SQLException { int row = 0; try { int currentRow = resultset.getRow(); // Remember old row position resultset.last(); row = resultset.getRow(); if (currentRow > 0) { resultset.absolute(row); } } catch (Exception ex) { ex.printStackTrace(); } return row; } /** * Get the column count of the result set. * * @param resultSet * ResultSet * @return int the column count */ public static int getColumnCount(ResultSet resultSet) { if (resultSet == null) { return 0; } try { ResultSetMetaData metaData = resultSet.getMetaData(); int numberOfColumns = metaData.getColumnCount(); return numberOfColumns; } catch (Exception ex) { ex.printStackTrace(); } return 0; } /** * Read one row's data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * @param resultSet * ResultSet * @return Hashtable */ public static final Hashtable readResultToHashtable(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { resultHash.put(columns[i], getString(resultSet, columns[i])); } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** * Read data from result set automatically and put the result it a * hashtable. Stored as "columnName" = "value", where value is converted to * String. * * Note: assume the default database string encoding is ISO8859-1. * * @param resultSet * ResultSet * @return Hashtable */ @SuppressWarnings("unchecked") public static final Hashtable readResultToHashtableISO(ResultSet resultSet) { if (resultSet == null) { return null; } Hashtable resultHash = new Hashtable(); try { String[] columns = getColumns(resultSet); if (columns != null) { // Read data column by column for (int i = 0; i < columns.length; i++) { String isoString = getString(resultSet, columns[i]); try { resultHash.put(columns[i], new String(isoString .getBytes("ISO8859-1"), "GBK")); } catch (Exception ex) { resultHash.put(columns[i], isoString); } } } } catch (Exception ex) { ex.printStackTrace(); } return resultHash; } /** Test this class. */ public static void main(String[] args) throws Exception { DatabaseUtil util = new DatabaseUtil(); // TODO: 从连接池工厂获取连接 // util.setConnection(ConnectionFactory.getConnection()); ResultSet rs = util.executeQuery("SELECT * FROM e_hyx_trans_info"); while (rs.next()) { Hashtable hash = readResultToHashtableISO(rs); Enumeration keys = hash.keys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); System.out.println(key + "=" + hash.get(key)); } } rs.close(); util.close(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值