英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论