To update records in an SQL database using Go, you will need to perform the following steps:
database/sql
package.import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
mysql
driver and connect to a MySQL database.db, err := sql.Open("mysql", "username:password@tcp(hostname:port)/database")
if err != nil {
log.Fatal(err)
}
defer db.Close()
Prepare
method of the database connection, prepare the SQL statement for updating records. Ensure to include the necessary placeholders (?
) for parameterized queries.stmt, err := db.Prepare("UPDATE tablename SET column1=?, column2=? WHERE condition_column=?")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
result, err := stmt.Exec(value1, value2, conditionValue)
if err != nil {
log.Fatal(err)
}
Result
object. You can check the number of affected rows using the RowsAffected
method.affectedRows, err := result.RowsAffected()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Number of affected rows: %d\n", affectedRows)
Here's the complete example of updating records in an SQL database with Go:
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
db, err := sql.Open("mysql", "username:password@tcp(hostname:port)/database")
if err != nil {
log.Fatal(err)
}
defer db.Close()
stmt, err := db.Prepare("UPDATE tablename SET column1=?, column2=? WHERE condition_column=?")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
result, err := stmt.Exec(value1, value2, conditionValue)
if err != nil {
log.Fatal(err)
}
affectedRows, err := result.RowsAffected()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Number of affected rows: %d\n", affectedRows)
}
Remember to replace username
, password
, hostname
, port
, database
, tablename
, column1
, column2
, and condition_column
with your corresponding values specific to your database setup. Also, provide the appropriate values for value1
, value2
, and conditionValue
based on your requirements.