在Go语言中使用goroutines将GET请求中的数据插入MySQL时出现的问题[已关闭]

q3qa4bjr  于 2023-02-03  发布在  Mysql
关注(0)|答案(1)|浏览(127)

昨天关门了。
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)
}
ki1q1bka

ki1q1bka1#

按照这个tutorial,它是非常详细的。你会看到,为了插入,你需要使用db.Exec,你需要传递值给它。你需要解析你的HTTP请求来提取这些值。

// addAlbum adds the specified album to the database,
// returning the album ID of the new entry
func addAlbum(alb Album) (int64, error) {
    result, err := db.Exec("INSERT INTO album (title, artist, price) VALUES (?, ?, ?)", alb.Title, alb.Artist, alb.Price)
    if err != nil {
        return 0, fmt.Errorf("addAlbum: %v", err)
    }
    id, err := result.LastInsertId()
    if err != nil {
        return 0, fmt.Errorf("addAlbum: %v", err)
    }
    return id, nil
}

相关问题