package com.zsxt; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; @SpringBootTest public class dept_List { @Test public static void main(String[] args) { //指定的接口,包含url String apiUrl = "***********"; //第三方接口需要体统令牌校验才能访问数据 String authorization = "************"; //本地数据库的地址、账号、密码 String dbUrl = "*************"; String dbUser = "*************"; String dbPassword = "*************"; writeDataToDatabase(apiUrl, authorization, dbUrl, dbUser, dbPassword); } public static void writeDataToDatabase(String apiUrl, String authorization, String dbUrl, String dbUser, String dbPassword) { try { // 发送 HTTP 请求获取接口内容,包含 Authorization 在请求头中 URL url = new URL(apiUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", authorization); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 解析 JSON 格式的接口内容,提取主要内容 String responseData = response.toString(); JSONObject jsonObject = new JSONObject(responseData); JSONArray mainContentArray = jsonObject.getJSONArray("data"); // 假设 JSON 数据的主要内容位于 mainContent 字段中 System.out.println(mainContentArray); System.out.println(mainContentArray.length()); System.out.println("运行成功"); // 连接数据库 Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword); // 假设数据库表已经存在,这里不再创建表 for (int i =0;i<mainContentArray.length();i++){ // 将数据写入数据库 String insertQuery = "INSERT INTO dept_list (deptName, deptId, parentId,deptCode) VALUES (?, ?, ?,?)"; PreparedStatement preparedStatement = conn.prepareStatement(insertQuery); // 设置预编译语句的参数,假设从主要内容中获取 preparedStatement.setString(1, mainContentArray.getJSONObject(i).getString("deptName")); preparedStatement.setString(2, mainContentArray.getJSONObject(i).getString("deptId")); preparedStatement.setString(3, mainContentArray.getJSONObject(i).getString("parentId")); preparedStatement.setString(4, mainContentArray.getJSONObject(i).getString("deptCode")); // ... // 执行插入操作 preparedStatement.executeUpdate(); // 关闭连接 preparedStatement.close(); } conn.close(); System.out.println("Data has been successfully written to the database."); } catch (IOException | SQLException e) { e.printStackTrace(); } catch (JSONException e) { throw new RuntimeException(e); } } }
通过JAVA的第三方接口向数据库插入数据
最新推荐文章于 2024-05-31 19:06:55 发布