手记

获取数据库数据进行json拼接

package cn.gool.test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import com.alibaba.fastjson.JSON;

/**

  • author:gool

  • date:2017年12月13日
    */
    public class ConvertJson implements Runnable {

    private String driver;
    private String url;
    private String user;
    private String pwd;

    public ConvertJson(String driver, String url, String user, String pwd) {
    this.driver = driver;
    this.url = url;
    this.user = user;
    this.pwd = pwd;
    }

    @Override
    public void run() {

    try {    Class.forName(driver);    Connection con = DriverManager.getConnection(url, user, pwd);    Statement stet = con.createStatement();    // String sql = "select device_info from gool where id<10000";    String sql = "select device_info from gool";    ResultSet rs = stet.executeQuery(sql);    ResultSetMetaData metaData = rs.getMetaData();    int columnCount = metaData.getColumnCount();    StringBuffer sb = new StringBuffer();    // sb.append("[");    while (rs.next()) {        for (int i = 1; i <= columnCount; i++) {            String columnName = metaData.getColumnLabel(i);            String value = rs.getString(columnName);            try {                Object parse = JSON.parse(value);                if (parse != null) {                    // sb.append(parse).append(",");                    sb.append(parse).append("\n");                }            } catch (Exception e) {                e.printStackTrace();                continue;            }        }    }    // sb.deleteCharAt(sb.length() - 1);    // sb.append("]");    // System.out.println(sb.toString());    File file = new File("gool.json");    if (!file.exists()) {        file.createNewFile();    }    FileWriter fileWritter = new FileWriter(file.getName(), true);    BufferedWriter bufferWritter = new BufferedWriter(fileWritter);    bufferWritter.write(sb.toString());    bufferWritter.close();    con.close();} catch (Exception e) {    e.printStackTrace();}

    }

}
package cn.gool.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import com.alibaba.fastjson.JSON;

public class Demo1 {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/zhnjdb";
String user = "root";
String pwd = "password";

//      for (int i = 0; i < 20; i++) {

        Thread thread = new Thread(new ConvertJson(driver,url,user,pwd));        thread.start();

//      }

}

}

0人推荐
随时随地看视频
慕课网APP