zoukankan      html  css  js  c++  java
  • 将数据库中的数据转换成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 }
  • 相关阅读:
    strncpy (Strings) – C 中文开发手册
    HTML track label 属性
    Java面试题:常用的Web服务器有哪些?
    鲲鹏920上安装ovs
    基于AC控制器+VXLAN解决方案
    二层MAC学习及BUM报文转发
    基于mac表的vxlan转发
    Agile Controller vxlan
    设置鲲鹏916/920通过pxe安装os
    ovs-vxlan&vlan
  • 原文地址:https://www.cnblogs.com/hellomandy/p/8054440.html
Copyright © 2011-2022 走看看