This question already has answers here:
Scan function by reference or by value
(1 answer)
I want to check if record exist and if not exist then i want to insert that record to database using golang
(4 answers)
Closed 2 years ago.
I currently have:
func foo (w http.ResponseWriter, req *http.Request) {
chekr := `SELECT FROM public."Users" WHERE email=$1`
err = db.QueryRow(chekr, usr.Email).Scan()
if err != sql.ErrNoRows {
data, err := json.Marshal("There is already a user with this email")
if err != nil { w.Write(data) }
}
// code that should run if email isn't found
}
However, I find it never working and always passing the if block.
As the above comment stated, I forgot the */1. QueryRow works, I just had another error somewhere. As others have stated there's others errors, this is just for one case to test.
Related
This question already has answers here:
Accessing Nested Map of Type map[string]interface{} in Golang
(2 answers)
Is there any convenient way to get JSON element without type assertion?
(2 answers)
invalid operation: type interface {} does not support indexing
(3 answers)
Closed last month.
I recently started studying Golang and I have a problem now, I can't find any information or documentetion about it :( Please, I need your help! I have some structure in mongodb:
"id": 123,
"attributes.store.name": TestStore
I need to get these values (id, name), I use this code:
...
opt := options.Find().SetProjection(bson.M{
"_id": 0,
"id": 1,
"attributes.store.name": 1})
opt.SetLimit(1) //1 just for test, I need to get 100000
var curr *mongo.Cursor
curr, err = visits.Find(context.Background(), filter, opt)
if err != nil {
log.Fatal(err)
}
var results []bson.M
if err = curr.All(context.Background(), &results); err != nil {
log.Fatal(err)
}
for _, result := range results {
fmt.Println(result)
}
But in this way I get:
[map[attributes:map[store:map[name:TestStore]] id:123]]
So I can't understand how I can get exactly "name", because I can use result["attributes"], but I can't get result["attributes"]["store"]["name"] because the result["attributes"] has a "primitive.M" type.
Is there maybe a way to "avoid" keys "attributes.store" in "attributes.store.name": 1?
Or how it possible to get the "name"?
And please give me a documentatial link about it, beacuse unfortunately I couldn't find anytithg about this case.
///////////////////////////////////////////////////////
I have tried this:
opt := options.Find().SetProjection(bson.M{
"_id": 0,
"id": 1,
"attributes.store.name": 1})
I expected to see:
[map[name:TestStore] id:123]]
I've got:
[map[attributes:map[store:map[name:TestStore]] id:123]]
This way I can't get the value under the key "name"
This question already has answers here:
How to make scanning DB rows in Go DRY?
(1 answer)
How to call the Scan variadic function using reflection
(4 answers)
Closed 8 months ago.
I am reading all rows from postgresql database using golang. This method working perfectly, but I need to reorganise the code in a productive way. Any help is much appreciated.
Here is the code:
type Books struct {
Name string
ISBN string
Author string
PublishedOn string
}
func GetBooks() {
db := Connection() // COnnection to postgres database
var books []Books
rows, err := db.Query("SELECT * FROM books")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
book := Books{}
err = rows.Scan(&book.Name, &book.ISBN, &book.Author, &book.PublishedOn)
books = append(books, book)
}
}
Here let us consider the struct has 20 fields and the row also have 20 columns. What is an effective method not to use &book.Name, &book.ISBN, &book.Author, &book.PublishedOn or some x number of columns and just include ONE single value
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am facing the above issue with the code below
stmt, err2 := db.Prepare( "SELECT COUNT(*) FROM xyz WHERE product_id=? and chart_number=?")
rows, err2 := stmt.Query( bidStatusReqVal.ProductId,bidStatusReqVal.ChartNumber).Scan(&count)
Query(...).Scan(...) is not valid because Query returns two values and chaining of calls requires that the previous call returns only one value. Call Scan on the returned rows, or use QueryRow(...).Scan(...) with only err as the return destination.
rows, err := stmt.Query(bidStatusReqVal.ProductId, bidStatusReqVal.ChartNumber)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
if err := rows.Scan(&count); err != nil {
return err
}
}
if err := rows.Err(); err != nil {
return err
}
// ...
In cases where the query returns only a single row, e.g. SELECT ... LIMIT 1, or SELECT COUNT(*) ... like in your case, it is much more convenient to use QueryRow.
err := stmt.QueryRow(bidStatusReqVal.ProductId, bidStatusReqVal.ChartNumber).Scan(&count)
if err != nil {
return err
}
// ...
This question already has answers here:
How do I insert multiple values into a postgres table at once?
(6 answers)
How to insert multiple data at once
(8 answers)
Closed 3 years ago.
In PostgreSQL I have a pretty simple table where I store information about relationships between users and games. Here is a working function which I use to insert data. As you can see it makes multiple SQL queries to the database which is not elegant I think. What do I need to change to insert multiple rows with one query?
var CreateRelationship = func(responseWriter http.ResponseWriter, request *http.Request) {
userID := mux.Vars(request)["user_id"]
type RequestBody struct {
Games []int `json:"games"`
}
requestBody := RequestBody{}
decoder := json.NewDecoder(request.Body)
if err := decoder.Decode(&requestBody); err != nil {
utils.ResponseWithError(responseWriter, http.StatusBadRequest, err.Error())
return
}
for i := 0; i < len(requestBody.Games); i++ {
if _, err := database.DBSQL.Exec("INSERT INTO users_games_relationship (user_id, game_id) VALUES ($1, $2);", userID, requestBody.Games[i]); err != nil {
utils.ResponseWithError(responseWriter, http.StatusInternalServerError, err.Error())
return
}
}
utils.ResponseWithSuccess(responseWriter, http.StatusOK, "All new records successfully created.")
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I want to batch insert some rows and get their ids with golang, this is my attempt in doing so
import (
"database/sql"
"fmt"
_ "github.com/bmizerany/pq"
"log"
)
func main() {
conn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=require", host, user, password, dbname)
d, err := sql.Open("postgres", conn)
rows, err := d.Query("INSERT INTO MYTABLE(MYCOLUMN) VALUES(1),(2),(3) RETURNING ID")
defer rows.Close()
var ids []int
for rows.Next() {
var id int
scan_err := rows.Scan(&id)
fmt.Println(scan_err)
if scan_err != nil {
log.Fatal(scan_err)
}
ids = append(ids, id)
fmt.Printf("id %d\n", id)
}
}
my problem is ids is always empty even if the values are inserted correctly in the database.
what's interesting is that the following works
var id int
db.QueryRow("INSERT INTO MYTABLE(MYCOLUMN) VALUES(1) RETURNING ID").Scan(&id)
How do solve this?