• 将数据库中的数据转换成Json


     1 import java.sql.*;
     2 import java.util.*;
     3 import org.json.*;//引入相关包,包含在json.jar里
     4 
     5 public class SqlJsonConvertor {
     6 public static void main(String[] args) {
     7     String driver = "com.mysql.jdbc.Driver";
     8     String url = "jdbc:mysql://localhost:3306/phpwind";
     9     String user = "root";
    10     String passwd = "123456";
    11     String sql = "select * from pw_acloud_apis";
    12     
    13     try {
    14         Class.forName(driver);
    15         Connection con = DriverManager.getConnection(url, user, passwd);
    16         Statement st =  con.createStatement();
    17         ResultSet rs = st.executeQuery(sql);
    18         ResultSetMetaData rsmd = rs.getMetaData();
    19         int colnum = rsmd.getColumnCount();
    20         String val = "";
    21         String colName = "";
    22         JSONObject jobj = new JSONObject();
    23         JSONArray jArr = new JSONArray();
    24         
    25         while(rs.next()) {
    26             for(int i = 1; i<= colnum; i++) {
    27                 colName = rsmd.getColumnLabel(i);
    28                 if(1==i) {
    29                     val = new Integer(rs.getInt(colName)).toString();
    30                 }else {
    31                     val = rs.getString(colName);
    32                 }
    33                 
    34                 try {
    35                     jobj.put(colName, val);
    36                     
    37                 } catch (JSONException e) {
    38                     // TODO Auto-generated catch block
    39                     e.printStackTrace();
    40                 }            
    41             }
    42             jArr.put(jobj);    
    43         }
    44         System.out.println("Here is the json String:");
    45         System.out.println(jArr.toString());
    46         
    47     }catch(ClassNotFoundException e) {
    48         System.out.println("Driver not found");
    49         e.printStackTrace();
    50     }catch(SQLException e) {
    51         e.printStackTrace();
    52     }    
    53 }
    54 }
  • 相关阅读:
    数据库外键约束
    mysql查询数据
    操作mysql操作数据库
    自定义标签
    jstl标签
    getattibute 与 getparameter区别
    2017.3.2
    java中静态,抽象,接口,继承总结
    关于使用css伪类实现小图标
    动态生成的dom元素绑定事件
  • 原文地址:https://www.cnblogs.com/hellomandy/p/8054440.html
Copyright © 2020-2023  润新知