Write Raw Queries and Use Query Builder
Learn to write raw SQL queries and use Query Builder to build complex queries using Beego ORM.
Writing raw SQL queries
In Beego ORM, we can write raw SQL queries using the Raw
method. This method takes a raw SQL query as a string. The Raw
method is chained with methods like QueryRows
, QueryRow
, and Exec
to execute the query and retrieve the results.
Here’s an example of how to use the Raw
method to execute a raw SQL query that selects all records from a users
table:
o := orm.NewOrm()var users []*Userres, err := o.Raw("SELECT * FROM users").QueryRows(&users)
In this example, User
is the struct that corresponds to the users
table. The QueryRows
function returns the number of rows retrieved in the res
variable, and any error that occurred in the err
variable.
The Exec
function can also be used to execute a raw SQL query that doesn’t return any results, such as an insert or update query:
res, err := o.Raw("UPDATE users SET name = ? WHERE id = ?", "RainboxRanger", 1).Exec()
The Exec()
function takes the query and the parameters as arguments and returns the number of rows affected in the res
...