使用Go和sqlx时遇到了“pq: syntax error at or near”的问题。

huangapple go评论220阅读模式
英文:

getting "pq: syntax error at or near" with Go and sqlx

问题

我有一个表:

  1. CREATE TABLE "order"
  2. (
  3. "order" jsonb NOT NULL
  4. );

我尝试使用这些代码和 sqlx 来操作数据库:

  1. func (r *RepositoryPostgres) CreateDocument(order L0.Order) error {
  2. tx := r.db.MustBegin()
  3. orderJSON, err := json.Marshal(order.OrderEntry)
  4. if err != nil {
  5. return err
  6. }
  7. tx.MustExec("INSERT INTO order (order) VALUES ($1)", orderJSON)
  8. err = tx.Commit()
  9. if err != nil {
  10. return err
  11. }
  12. return nil
  13. }
  14. func (r *RepositoryPostgres) GetAllDocuments() ([]L0.Order, error) {
  15. var documents []L0.Order
  16. err := r.db.Select(&documents, "SELECT * FROM order")
  17. if err != nil {
  18. return nil, err
  19. }
  20. return documents, nil
  21. }

但是我得到了错误 pq: syntax error at or near "order"。我的语法有什么问题?

英文:

I have table:

  1. CREATE TABLE "order"
  2. (
  3. "order" jsonb NOT NULL
  4. );

i try to work with bd with these codes using sqlx:

  1. func (r *RepositoryPostgres) CreateDocument(order L0.Order) error {
  2. tx := r.db.MustBegin()
  3. orderJSON, err := json.Marshal(order.OrderEntry)
  4. if err != nil {
  5. return err
  6. }
  7. tx.MustExec("INSERT INTO order (order) VALUES ($1)", orderJSON)
  8. err = tx.Commit()
  9. if err != nil {
  10. return err
  11. }
  12. return nil
  13. }
  1. func (r *RepositoryPostgres) GetAllDocuments() ([]L0.Order, error) {
  2. var documents []L0.Order
  3. err := r.db.Select(&documents, "SELECT * FROM order")
  4. if err != nil {
  5. return nil, err
  6. }
  7. return documents, nil
  8. }

but im getting error pq: syntax error at or near "order". What is the problem with my syntax?

答案1

得分: 3

"Order"是一个保留关键字,你需要用双引号将其括起来。
你可以在这里看到其他的保留关键字。

将你的代码修改如下:

第一个函数(第7行):

  1. tx.MustExec("INSERT INTO \"order\" (\"order\") VALUES ($1)", orderJSON)

第二个函数(第3行):

  1. err := r.db.Select(&documents, "SELECT * FROM \"order\"")

注意:这只是一个临时解决方案,最好是修改表名。

英文:

"Order" is a reserved keyword, you will need to enclose it in double quotes.
You can see other reserved keywords here.

Change your code as follows:

1st Function (Line-7):

  1. tx.MustExec("INSERT INTO \"order\" (\"order\") VALUES ($1)", orderJSON)

2nd Function (Line-3):

  1. err := r.db.Select(&documents, "SELECT * FROM \"order\"")

Note: Its a temporary solution, it is better to change the table name.

huangapple
  • 本文由 发表于 2023年6月25日 18:09:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76549878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定