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 }
  • 相关阅读:
    Cisco网络模拟器踩坑记录
    PAT甲级1009水题飘过
    PAT甲级1011水题飘过
    springmvc中项目启动直接调用方法
    Eclipse中Java文件图标由实心J变成空心J的问题
    mysql求时间差
    maven常用命令
    java单例模式(两种常用模式)
    mybatis一对多,多对一
    mybatis简介
  • 原文地址:https://www.cnblogs.com/hellomandy/p/8054440.html
Copyright © 2011-2022 走看看