Answer the question
In order to leave comments, you need to log in
How to iterate over an array and insert into a database?
How to iterate through the array and write everything to the database?
There is an example of the usual iteration of an array with output to the console
package main
import "fmt"
type User struct {
UserName string
Category string
Age int
}
type Users []User
func (u Users) NameList() []string {
var list []string
for _, user := range u {
list = append(list, user.UserName)
}
return list
}
func main() {
users := Users{
User{UserName: "Bryan", Category: "Human", Age: 33},
User{UserName: "Jane", Category: "Rocker", Age: 25},
User{UserName: "Nancy", Category: "Mother", Age: 40},
User{UserName: "Chris", Category: "Dude", Age: 19},
User{UserName: "Martha", Category: "Cook", Age: 52},
}
UserList := users.NameList()
fmt.Println(UserList)
}
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
panic(err)
}
defer db.Close()
Answer the question
In order to leave comments, you need to log in
If you take your code as a basis, something like this can be done
package main
import "fmt"
type User struct {
UserName string
Category string
Age int
}
func main() {
users := []User{
User{UserName: "Bryan", Category: "Human", Age: 33},
User{UserName: "Jane", Category: "Rocker", Age: 25},
User{UserName: "Nancy", Category: "Mother", Age: 40},
User{UserName: "Chris", Category: "Dude", Age: 19},
User{UserName: "Martha", Category: "Cook", Age: 52},
}
// подключаетесь к базе
db, _ := sql.Open(...)
defer db.Close()
for _, user := range users {
fmt.Println(user)
// делаете запрос в базу
db.Exec("INSERT INTO users (name, category, age) VALUES ($1, $2, $3)", user.UserName, user.Category, user.Age)
}
}
tx, _ := db.Begin() // начинаете транзакцию
for _, user := range users {
fmt.Println(user)
// делаете запрос в базу (тут уже не db, а tx.Exec)
tx.Exec("INSERT INTO users (name, category, age) VALUES ($1, $2, $3)", user.UserName, user.Category, user.Age)
}
tx.Commit() // завершаете транзакцию, данные сохраняются в базе
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question