Junior — Middle
How was the insertion of a new column into a database table carried out?
sobes.tech AI
Answer from AI
Adding a new column to a database table is usually done using the SQL command ALTER TABLE. In Go (Golang), you can use the database/sql package to execute the corresponding SQL query.
Example of adding a new_column of type VARCHAR(255) to the users table:
import (
"database/sql"
_ "github.com/lib/pq" // example for PostgreSQL
"log"
)
func addColumn(db *sql.DB) error {
query := `ALTER TABLE users ADD COLUMN new_column VARCHAR(255);`
_, err := db.Exec(query)
return err
}
func main() {
db, err := sql.Open("postgres", "user=postgres dbname=mydb sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err := addColumn(db); err != nil {
log.Fatalf("Error adding column: %v", err)
}
log.Println("Column successfully added")
}
Thus, adding a column involves executing an SQL command through Go code.