Updating existing data
When you are updating a row or multiple rows with Go, you are in trouble. The sql
package does not provide any function called Update()
; however, there is the Exec()
function, which serves as a universal executor for your queries. You can execute SELECT
, UPDATE
, DELETE
, or whatever you need to execute with this function. This section will show you how you can do this safely.
We would like to start our script in the usual way. It can be found in the examples folder and is called DBUpdate.go
:
package main import "fmt" import "database/sql" import _ "github.com/lib/pq"
Then the magic comes. The idea is to update the name
column’s value for a specific id
variable that we give as an argument. So, the main()
function looks like this:
func main(){ db, err := sql.Open("postgres", "user=postgres password=Start!123 host=127.0.0.1 port=5432 dbname=postgres sslmode=disable") if err...