我可不是光会用现成库滴,看代码

mallon 发布于 2014/03/19 18:29
阅读 680
收藏 4

MySQL连接为什么挂死了?别踩坑!>>>

Db.java

package netvis;

import org.postgresql.ds.PGPoolingDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * 数据库查询更新
 */
public class Db {
    private static final Logger logger = Logger.getLogger(Db.class.getCanonicalName());
    private static PGPoolingDataSource source = null;

    static {
        source = new PGPoolingDataSource();
        source.setDataSourceName("Default Data Source");
        source.setServerName("localhost");
        source.setPortNumber(5432);
        source.setDatabaseName("netvis");
        source.setUser("postgres");
        source.setPassword("");
        source.setMaxConnections(8);
    }

    private static PreparedStatement prepareStatement(Connection conn, String sql, Object... params) throws Exception {
        PreparedStatement stmt = conn.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            stmt.setObject(i + 1, params[i]);
        }
        return stmt;
    }

    /**
     * 查询操作
     *
     * @param sql    SQL语句
     * @param params SQL语句中的参数
     * @return MapList结构的查询结果
     * @throws Exception
     */
    public static List<Map<String, Object>> query(String sql, Object... params) throws Exception {
        try (Connection conn = source.getConnection()) {
            PreparedStatement stmt = prepareStatement(conn, sql, params);
            ResultSet rs = stmt.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            List<Map<String, Object>> result = new ArrayList<>();
            while (rs.next()) {
                Map<String, Object> row = new HashMap<>();
                for (int i = 0; i < colCount; i++) {
                    row.put(rsmd.getColumnLabel(i + 1), rs.getObject(i + 1));
                }
                result.add(row);
            }
            return result;
        }
    }

    /**
     * 更新操作
     *
     * @param sql    SQL语句
     * @param params SQL语句中的参数
     * @return 更新的行数
     * @throws Exception
     */
    public static int update(String sql, Object... params) throws Exception {
        try (Connection conn = source.getConnection()) {
            PreparedStatement stmt = prepareStatement(conn, sql, params);
            return stmt.executeUpdate();
        }
    }
}



Json.java
package netvis;

import java.util.*;
import java.util.logging.Logger;

/**
 * JSON包装解析
 */
public class Json {
    private static final Logger logger = Logger.getLogger(Json.class.getCanonicalName());
    private static char[] hex = "0123456789ABCDEF".toCharArray();

    private static void dumpString(StringBuilder sb, String str, boolean escape) {
        sb.append('"');
        for (char c : str.toCharArray()) {
            switch (c) {
                case '"':
                    sb.append("\\\"");
                    break;
                case '\\':
                    sb.append("\\\\");
                    break;
                case '/':
                    sb.append("\\/");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                default:
                    int n = (int) c;
                    // 超出ASCII可打印字符范围的Unicode转义
                    if ((n < 0x20 || n > 0x7E) && escape) {
                        sb.append("\\u");
                        for (int i = 0; i < 4; ++i) {
                            int digit = (n & 0xf000) >> 12;
                            sb.append(hex[digit]);
                            n <<= 4;
                        }
                    } else {
                        sb.append(c);
                    }
            }
        }
        sb.append('"');
    }

    private static void indent(StringBuilder sb, int level) {
        for (int i = 0; i < level * 4; i++) {
            sb.append(' ');
        }
    }

    private static void dumpRecursively(StringBuilder sb, Object obj, int level, Boolean indent, Boolean escape) {
        if (obj == null) {
            sb.append("null");
        } else if ((obj instanceof Boolean) || (obj instanceof Number)) {
            sb.append(obj.toString());
        } else if (obj instanceof Map) {
            sb.append('{');
            if (indent) {
                sb.append('\n');
            }
            Map map = ((Map) obj);
            Set keys = map.keySet();
            int keyCount = keys.size();
            int n = 0;
            for (Object key : keys) {
                if (indent) {
                    indent(sb, level + 1);
                }
                dumpString(sb, key.toString(), escape);
                sb.append(':');
                if (indent) {
                    sb.append(' ');
                }
                dumpRecursively(sb, map.get(key), level + 1, indent, escape);
                n++;
                if (n < keyCount) {
                    sb.append(',');
                }
                if (indent) {
                    sb.append('\n');
                }
            }
            if (indent) {
                indent(sb, level);
            }
            sb.append('}');
        } else if (obj instanceof List) {
            sb.append('[');
            if (indent) {
                sb.append('\n');
            }
            List list = (List) obj;
            int listSize = list.size();
            int n = 0;
            for (Object elem : list) {
                if (indent) {
                    indent(sb, level + 1);
                }
                dumpRecursively(sb, elem, level + 1, indent, escape);
                n++;
                if (n < listSize) {
                    sb.append(',');
                }
                if (indent) {
                    sb.append('\n');
                }
            }
            if (indent) {
                indent(sb, level);
            }
            sb.append(']');
        } else {
            // 其它通通toString()
            dumpString(sb, obj.toString(), escape);
        }
    }

    /**
     * 将Java对象转换成Json字符串
     *
     * @param obj    Java对象
     * @param indent 是否缩进
     * @param escape 是否转义非可打印ASCII字符以及ASCII之外的其它Unicode字符
     * @return Json字符串
     */
    public static String dump(Object obj, Boolean indent, Boolean escape) {
        StringBuilder sb = new StringBuilder();
        dumpRecursively(sb, obj, 0, indent, escape);
        return sb.toString();
    }

    public static String dump(Object obj) {
        return dump(obj, true, false);
    }

    public static void main(String... args) {
        System.out.println(dump(new HashMap<String, Object>() {{
            put("你好", null);
            put("世界", new ArrayList<Object>() {{
                add(null);
                add(true);
                add(123.456E11);
                add("Hello World\n");
                add(new HashMap<String, Object>() {{
                    put("a", "aaa");
                }});
            }});
        }}, true, false));
    }
}



Test.java
package test;

import netvis.Db;
import netvis.Json;

/**
 * 测试
 */
public class Test {

    public static void main(String... args) throws Exception {
        for (; ; ) {
            System.out.println(Json.dump(Db.query("select id::text, name from test")));
        }
    }
}



加载中
0
宏哥
宏哥

浪费生命, Man

你需要得到的是那些值得你争取的认可

那些小码农, 不用理他们, 他们没有两个凡是的指引, 全都是怪胎

mallon
mallon
要不是工作需要,才懒得折腾这些东西呢。只能在无聊的工作之余上OSC逗逗那些Javaer寻开心了,哈哈
0
FOG_Y
FOG_Y

我觉得直接去学习库代码会是你下一步需要做的。。。。

如果你能经过测试后发现你的代码效率高于库,那么你的代码是很值得推崇的! 

0
阿诶么刚阿
阿诶么刚阿
太不成熟了孩子
0
0
大王叫我来卖萌
大王叫我来卖萌
不要活在别人的阴影下
0
ththththht
ththththht
情商不行,智商再高也是没用的。
0
滔哥
滔哥
别浪费太多脑细胞啦
0
_Aaron_
_Aaron_

我是小码农啊,我是小码农~~

返回顶部
顶部