json格式数据导入到mysql

JDBCUTIL

可能用到的依赖:
 
            c3p0
            c3p0
            0.9.1.2
        


代码:
import java.sql.Connection;
import java.sql.SQLException;


import org.apache.commons.dbutils.QueryRunner;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 1. 获取数据源
 * 2. 获取连接对象
 * 3. 返回dbutils的QueryRunner对象
 */
public class JDBCUtil {
	private static ComboPooledDataSource dataSource = null;
	static {
		dataSource = new ComboPooledDataSource();
	}
	/**
	 * 1.获取数据库连接对象 (事务),这个连接对象需要手动释放
	 * @return
	 */
	public static Connection getConnection() {
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 2.获取dbutils的QueryRunner对象(非事务),资源会自动释放
	 * @return 
	 */
	public static QueryRunner getQueryRunner() {
		return new QueryRunner(dataSource);
	}
	
}

 

/*
*  json依赖
*  
            net.sf.json-lib
            json-lib
            2.4
            jdk15
        
*/
public class JsonTOmysql {
    public static void main(String[] args)  {
       String path="C:\\Users\\WANG\\Desktop\\spark项目\\userInfo.json";
          try {
            try {
                readFromFile(path);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void readFromFile(String path) throws IOException, SQLException {
        BufferedReader br = new BufferedReader(
                new FileReader(path));
        String line = null;
        while ((line = br.readLine()) != null) {

            JSONObject responseJson = JSONObject.fromObject(line);
            Object user_id = responseJson.get("user_id");
            Object username = responseJson.get("username");
            Object name = responseJson.get("name");
            Object age = responseJson.get("age");
            Object professional = responseJson.get("professional");
            Object city = responseJson.get("city");
            Object sex = responseJson.get("sex");
            String sql = "insert into user_info values (?,?,?,?,?,?,?)";
            Object [] params = {user_id,username,name,age,professional,city,sex};
            QueryRunner qr = JDBCUtil.getQueryRunner();
             qr.update(sql,params);

          }
        br.close();
    }
}

 

你可能感兴趣的:(数据库)