Reputation: 11049
I am trying to query a database using database/sql
and the github.com/lib/pq
Postgres driver. The error I'm encountering is:
pq: relation "itemprices_itemsale" does not exist
However looking at my query:
rows, err := db.Query("SELECT * FROM \"itemPrices_itemsale\" LIMIT 10")
You'll notice the capital 'P' in the table name. I've learned form poking around that Postgres will fold names in to lowercase if they are not quoted. I have quoted my table name so I'm not quite sure why this is happening. I'm fairly certain this is the issue as I'm able to query the table using that table name from a similar Python program and everything is working as expected.
Update: Using @JohnWeldon's suggestion:
var table = "itemPrices_itemsale"
rows, err := db.Query(fmt.Sprintf("SELECT * FROM %s LIMIT 10", pq.QuoteIdentifier(table)))
Upvotes: 1
Views: 785
Reputation: 617
The accepted answer works and may avoid SQL injections when receiving the table name from an untrusted source, but is a bit verbose for a simple query.
You can just use backsticks and quote the table name manually:
rows, err := db.Query(`SELECT * FROM "itemPrices_itemsale" LIMIT 10`)
Upvotes: 0
Reputation: 40789
Try using the QuoteIdentifier
function in github.com/lib/pq
to quote your table name:
https://godoc.org/github.com/lib/pq#QuoteIdentifier
Upvotes: 2