用java写一个调用api接口存入数据库的代码
时间: 2024-05-12 14:16:10 浏览: 10
好的,以下是一个用Java调用API接口并将数据存入数据库的示例代码:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.json.JSONArray;
import org.json.JSONObject;
public class APICall {
public static void main(String[] args) {
Connection conn = null;
try {
// Connect to the database
String url = "jdbc:mysql://localhost/mydatabase";
String user = "root";
String password = "password";
conn = DriverManager.getConnection(url, user, password);
// Call the API and get the data
URL apiUrl = new URL("api_endpoint_url¶ms");
HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
connection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Parse the JSON response and insert into the database
JSONArray data = new JSONArray(response.toString());
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
PreparedStatement statement = conn.prepareStatement("INSERT INTO mytable (column1, column2, column3) VALUES (?, ?, ?)");
statement.setString(1, object.getString("field1"));
statement.setInt(2, object.getInt("field2"));
statement.setDouble(3, object.getDouble("field3"));
statement.executeUpdate();
}
// Close the database connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
```
这段代码可以连接到MySQL数据库,并从一个API接口中获取数据,然后将数据存入数据库。在实际使用时,需要将`api_endpoint_url¶ms`部分替换成实际的API接口地址和参数。同时也需要将数据库连接信息和SQL语句中的表名和列名替换成实际的值。