Single quote crasches Go

I have an insert routine that not accept single quote in the inserted text:

single'quote

The query:

INSERT INTO posts (post_subject,post_desc,post_type,post_status) VALUES ('single'quote','test',0,0) RETURNING post_id

The Go code:

func Insert(query string) int {
	id := 0
	err := db.QueryRow(query).Scan(&id)
	if err != nil {
		log.Fatal(err)
	}
	return id
}

This crashes Go and I get an answer:

pq: syntax error at or near "quote"

My question is if there is any way but “replaceall” for every and each field? Sometimes you want a single quote in your text. Is there a global setting “allow singlequotes”? I know I can use ` (backticks), but is there no other way?

How do you build the INSERT string? is single'quote the value of some string you use to build the SQL?

DB.QueryRow supports placeholders:

row := db.QueryRow("INSERT INTO foo (col) VALUES ($1)", "single'quote")

I need a return value? Possible with db.Exec?

INSERT INTO posts (post_subject,post_desc,post_type,post_status) VALUES ('single'quote','test',0,0) RETURNING post_id

That is a string, yes. But how do you build it? As it is right now, it is not valid SQL.

See my updated answer above.

You pointed me in the right direction. This works now. Thank you!

query := "INSERT INTO posts (post_subject,post_desc,post_type,post_status) 
VALUES ($1, $2, 0, 0)
RETURNING post_id"

subject := r.FormValue("subject")
desc := r.FormValue("desc")
id := Insert(query, subject, desc)

The query:

func Insert(query string, subject string, desc string) int {
id := 0
	err := db.QueryRow(query, subject, desc).Scan(&id)
	if err != nil {
		log.Fatal(err)
	}
	return id
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.