您当前的位置:首页 > 网站建设 > Mysql
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 |

json格式数据导入到mysql

51自学网 2022-01-13 11:27:45
  Mysql

json格式数据导入到mysql

 

JDBCUTIL

可能用到的依赖:
 <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>


代码:
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依赖
*  <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
*/
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();
    }
}

 


返回列表
mysql5.5用户修改自己的账号密码:
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1