The go database/sql package is a built-in library for interacting with SQL databases. It provides a uniform interface for queries and transactions, allowing developers to write database-agnostic code.
// Query the database rows, err := db.Query("SELECT * FROM users") if err != nil { panic(err.Error()) } defer rows.Close()
// Print query results for rows.Next() { var id int var name string var email string err = rows.Scan(&id, &name, &email) if err != nil { panic(err.Error()) } fmt.Printf("ID: %d, Name: %s, Email: %s\n", id, name, email) }
// Insert record into table insert, err := db.Query("INSERT INTO users(name, email) VALUES('John Doe', '[email protected]')") if err != nil { panic(err.Error()) } defer insert.Close() }
In this example, we are using the go-sql-driver/mysql package to connect to a MySQL database. We first open a connection using the sql.Open() function and defer closing the connection with db.Close(). We then perform a query to select all records from the users table, and print the results using a loop and rows.Scan(). Finally, we insert a new record into the table using db.Query().
The package library used in this example is "database/sql" and "github.com/go-sql-driver/mysql".
Golang DB.Query - 30 examples found. These are the top rated real world Golang examples of database/sql.DB.Query extracted from open source projects. You can rate examples to help us improve the quality of examples.