1. 程式人生 > >將資料庫查詢結果快速生成markdown格式表格

將資料庫查詢結果快速生成markdown格式表格

在寫資料庫相關博文時,經常需要把結果集展示到頁面上。用圖片真的是太麻煩了,一篇文章都沒寫完我就已經忍無可忍了。
於是寫了一段程式碼來生成基礎的markdown格式表格程式碼。

import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import
com.ibatis.sqlmap.client.SqlMapClientBuilder; import connTest.conn.SqlmapFactory; /** * * @author nayi224 * */ public class MarkDown { private static SqlMapClient client = null; private static String configFile = "config/SqlMapConfig.xml"; private static Reader r = null; static
{ try { r = Resources.getResourceAsReader(configFile); client = SqlMapClientBuilder.buildSqlMapClient(r); } catch (IOException e) { e.printStackTrace(); } } /** * @param args * @throws SQLException */ public static
void main(String[] args) throws SQLException { // TODO Auto-generated method stub List<LinkedHashMap> l2 = client.queryForList("blog.test"); System.out.println("\r\r"); prt(l2); } private static void prt(List<LinkedHashMap> list){ if(list == null || list.size() == 0) return; LinkedHashMap temp = list.get(0); String str = "|"; for(Object obj: temp.keySet()){ str += obj + "|"; } str += "\r|"; for(Object obj: temp.keySet()){ str += "----|"; } for(LinkedHashMap tempMap: list){ str += "\r|"; for(Object obj: tempMap.keySet()){ str += (tempMap.get(obj) == null ? "" : tempMap.get(obj)) + "|"; } } System.out.println(str); } }

生成資料例

|DEPT_ID|PARENT_ID|DEPT_NAME|DEPT_RANK|VAL|
|----|----|----|----|----|
|root||全國|/root|0|
|root_1|root|北京市|/root/root_1|2000|
|ln_root|root|遼寧省|/root/ln_root|200|
|ln_ys|ln_root|遼寧省瀋陽市|/root/ln_root/ln_ys|1000|
|ln_sy_hp|ln_ys|遼寧省瀋陽和平區|/root/ln_root/ln_ys/ln_sy_hp|500|
|ln_ys_dd|ln_ys|遼寧省瀋陽大東區|/root/ln_root/ln_ys/ln_ys_dd|600|
|jl_root|root|吉林省|/root/jl_root|0|
|jl_jl|jl_root|吉林省吉林市|/root/jl_root/jl_jl|200|
|jl_cc|jl_root|吉林省長春市|/root/jl_root/jl_cc|500|

終於不怕強迫症復發,一張圖截n遍了。