标签:cut bsp name manager span ext zhang except 下载
后端用get或者post从数据库取的数据如何打包成json:
需要下载json的jar包,这里有:http://download.csdn.net/detail/zhangy0329/607838
Connection ct = null; Statement sm = null; ResultSet rs = null; try{ Class.forName("com.mysql.jdbc.Driver"); //连接mysql数据库 ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8","用户名" , "密码"); sm = ct.createStatement(); rs = sm.executeQuery("select *from 表名"); JSONArray jsonData = JSONArray.fromObject(convertList(rs)); //先转成List格式,再转成json格式 System.out.println(jsonData.toString()); PrintWriter out = response.getWriter(); //把json数据传递到前端 out.print(jsonData); } catch(Exception ex) { //error 代码 }
数据库取的数据转成List的操作函数:
private static List convertList(ResultSet rs) throws SQLException { List list = new ArrayList(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCount(); while (rs.next()) { Map rowData = new HashMap(); for (int i = 1; i <= columnCount; i++) { rowData.put(md.getColumnName(i), rs.getObject(i)); } list.add(rowData); } return list; }
标签:cut bsp name manager span ext zhang except 下载
原文地址:http://www.cnblogs.com/Forever-Road/p/6107031.html