SQL Builders for Go
There are several SQL builders available for Go that are not ORMs. Here are some popular ones:
1. sqlx
- Repository: https://github.com/jmoiron/sqlx
- Description: sqlx is a popular SQL builder that extends the standard
database/sql package. It provides a simple and efficient way to build SQL queries.
2. sqlkit
- Repository: https://github.com/go-pg/sqlkit
- Description: sqlkit is a SQL builder that allows you to build SQL queries using a fluent API. It supports PostgreSQL, MySQL, and SQLite.
3. sqlbuilder
- Repository: https://github.com/huandu/golang-sqlbuilder
- Description: sqlbuilder is a SQL builder that provides a simple and easy-to-use API for building SQL queries. It supports various databases, including MySQL, PostgreSQL, and SQLite.
4. sqlc
Comparison
| SQL Builder | Complexity | Performance | Database Support |
|---|
| sqlx | Low | High | Various |
| sqlkit | Medium | Medium | PostgreSQL, MySQL, SQLite |
| sqlbuilder | Low | Medium | Various |
| sqlc | High | High | Various |
Example with sqlx
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type User struct {
ID int `db:"id"`
Username string `db:"username"`
}
func main() {
// Connect to the database
db, err := sqlx.Connect("mysql", "user:password@tcp(localhost:3306)/dbname")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
// Build a SQL query
query := "SELECT * FROM users WHERE username = :username"
users, err := db.NamedQuery(query, sqlx.Map{"username": "john"})
if err != nil {
fmt.Println(err)
return
}
// Scan the results
for _, user := range users {
fmt.Printf("ID: %d, Username: %s\n", user.ID, user.Username)
}
}
Example with sqlbuilder
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/huandu/golang-sqlbuilder"
)
type User struct {
ID int
Username string
}
func main() {
// Connect to the database
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
// Build a SQL query
builder := sqlbuilder.NewMySQLBuilder()
query, args := builder.Select("id", "username").
From("users").
Where("username = ?", "john").
Build()
// Execute the query
rows, err := db.Query(query, args...)
if err != nil {
fmt.Println(err)
return
}
defer rows.Close()
// Scan the results
for rows.Next() {
var user User
err = rows.Scan(&user.ID, &user.Username)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("ID: %d, Username: %s\n", user.ID, user.Username)
}
}
Based on popularity and ease of use, sqlx is a good choice for building SQL queries in Go. However, the best SQL builder for your project depends on your specific needs and requirements.