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

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

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

问题

我有一个表:

CREATE TABLE "order"
(
    "order" jsonb NOT NULL
);

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

func (r *RepositoryPostgres) CreateDocument(order L0.Order) error {
    tx := r.db.MustBegin()

    orderJSON, err := json.Marshal(order.OrderEntry)
    if err != nil {
        return err
    }

    tx.MustExec("INSERT INTO order (order) VALUES ($1)", orderJSON)
    err = tx.Commit()

    if err != nil {
        return err
    }
    return nil
}

func (r *RepositoryPostgres) GetAllDocuments() ([]L0.Order, error) {
    var documents []L0.Order

    err := r.db.Select(&documents, "SELECT * FROM order")
    if err != nil {
        return nil, err
    }

    return documents, nil
}

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

英文:

I have table:

CREATE TABLE "order"
(
    "order" jsonb NOT NULL
);

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


func (r *RepositoryPostgres) CreateDocument(order L0.Order) error {
	tx := r.db.MustBegin()

	orderJSON, err := json.Marshal(order.OrderEntry)
	if err != nil {
		return err
	}

	tx.MustExec("INSERT INTO order (order) VALUES ($1)", orderJSON)
	err = tx.Commit()

	if err != nil {
		return err
	}
	return nil
}

func (r *RepositoryPostgres) GetAllDocuments() ([]L0.Order, error) {
	var documents []L0.Order

	err := r.db.Select(&documents, "SELECT * FROM order")
	if err != nil {
		return nil, err
	}

	return documents, nil
}

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

答案1

得分: 3

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

将你的代码修改如下:

第一个函数(第7行):

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

第二个函数(第3行):

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):

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

2nd Function (Line-3):

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:

确定