- 已关闭**。此问题需要details or clarity。当前不接受答案。
- 想要改进此问题?**添加详细信息并通过editing this post阐明问题。
昨天关门了。
Improve this question
JSONPlaceholder(https://jsonplaceholder.typicode.com/)包含用户的帖子/帖子?userId = 7和帖子的评论/评论?postId = {postId}。任务是为id = 7的用户获取帖子,并为每个收到的帖子并行获取评论。我们还需要使用go-sql-driver/mysql将所有收到的评论并行写入MySQL数据库。
我们希望在收到帖子的信息后尽快征求意见。以下是整个过程的大致轮廓:
下面你可以看到我的尝试:
1.向user7的帖子提供GET请求
1.连接到MySQL数据库并将get请求中的数据插入数据库
所有这一切现在都没有并发性,原因现在的问题是实际插入数据从获得请求到数据库。
救命啊!
package main
import (
"database/sql"
"fmt"
"io"
"net/http"
_ "github.com/go-sql-driver/mysql"
)
// type Posts struct {
// UserId int `json:"userId"`
// Id int `json:"id"`
// Title string `json:"title"`
// Body string `json:"body"`
// }
// type Comments struct {
// PostId int `json:"postId"`
// Id int `json:"id"`
// Name string `json:"name"`
// Email string `json:"email"`
// Body string `json:"body"`
// }
func getRequest(url string) {
resp, err := http.Get(url)
if err != nil {panic(err)}
body, _ := io.ReadAll(resp.Body)
defer resp.Body.Close()
writeToDB(string(body))
}
func writeToDB(values string) {
//Connecting to DB
db, err := sql.Open("mysql", "root:root@tcp(127.0.0.1:8889)/comments")
if err != nil {panic(err)}
defer db.Close()
fmt.Println("Connetcted to MySQL")
//Inserting data
insert, err := db.Query("INSERT INTO `posts` (`userId`, `id`, `title`, `body`)", values)
if err != nil {panic(err)}
defer insert.Close()
}
func main() {
urlPosts := "https://jsonplaceholder.typicode.com/posts?userId=7"
getRequest(urlPosts)
}
1条答案
按热度按时间ki1q1bka1#
按照这个tutorial,它是非常详细的。你会看到,为了插入,你需要使用
db.Exec
,你需要传递值给它。你需要解析你的HTTP请求来提取这些值。