import ( "upper.io/db.v3" "upper.io/db.v3/postgresql" ) // Create a connection to a PostgreSQL database. sess, err := postgresql.Open(postgresql.ConnectionURL{ Host: "localhost", Database: "mydatabase", User: "myuser", Password: "mypassword", }) // Define a struct representing the table schema. type MyTable struct { ID uint `db:"id,omitempty"` Name string `db:"name"` Email string `db:"email"` } // Create a collection object referring to the table. collection := sess.Collection("mytable") // Insert a new record. myData := MyTable{Name: "John", Email: "[email protected]"} res, err := collection.Insert(myData) if err != nil { panic(err) } // Print the ID of the new record. fmt.Println(res.(string)) // Get a record by ID. var record MyTable err = collection.Find(db.Cond{"id": 1}).One(&record) if err != nil { panic(err) } // Print the record. fmt.Println(record) // Update a record. newData := MyTable{ID: 1, Name: "John Doe", Email: "[email protected]"} err = collection.Update(newData) if err != nil { panic(err) } // Delete a record. err = collection.Remove(db.Cond{"id": 1}) if err != nil { panic(err) }
import ( "upper.io/db.v3" "upper.io/db.v3/mysql" ) // Create a connection to a MySQL database. sess, err := mysql.Open(mysql.ConnectionURL{ Host: "localhost", Database: "mydatabase", User: "myuser", Password: "mypassword", }) // Define a struct representing the table schema. type MyTable struct { ID uint `db:"id,omitempty"` Name string `db:"name"` Email string `db:"email"` } // Create a collection object referring to the table. collection := sess.Collection("mytable") // Count the number of records in the table. count, err := collection.Find().Count() if err != nil { panic(err) } fmt.Printf("There are %d records in the table.\n", count) // Find all records where the name contains "John". var records []MyTable err = collection.Find(db.Cond{"name LIKE": "%John%"}).All(&records) if err != nil { panic(err) } // Print the records. for _, record := range records { fmt.Println(record) } // Find the record with the highest ID. var maxID uint err = collection.Find().OrderBy("-id").Limit(1).One(db.Field(&maxID)) if err != nil { panic(err) } fmt.Printf("The highest ID in the table is %d.\n", maxID)This example showcases various ways to query records using the Database Collection package in combination with the MySQL driver. Package library: upper.io.db