To connect to an SQL database in Go, you can use the database/sql package, which provides a general interface around SQL (or SQL-like) databases. Here's a step-by-step approach to connect to an SQL database in Go:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql" // or the driver package for your specific database
)
Open
function from the database/sql
pacakge, providing the driver name and connection string:db, err := sql.Open("mysql", "username:password@tcp(hostname:port)/database_name")
if err != nil {
// handle error if connection fails
}
defer db.Close() // close the connection when you're done
err = db.Ping()
if err != nil {
// handle error if connection is unsuccessful
}
db
instance. For example, you can query data from the database:rows, err := db.Query("SELECT * FROM table_name")
if err != nil {
// handle error if query fails
}
defer rows.Close() // close query result when you're done
// process the rows returned by the query
for rows.Next() {
var column1 string
var column2 int
err = rows.Scan(&column1, &column2)
if err != nil {
// handle error if scanning values fails
}
// process the values retrieved from the database
}
stmt, err := db.Prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)")
if err != nil {
// handle error if prepare statement fails
}
defer stmt.Close() // close prepared statement when you're done
_, err = stmt.Exec("value1", 42) // execute the statement with actual values
if err != nil {
// handle error if execution fails
}
Remember to handle error cases appropriately in your code. This is just a basic example to get started with connecting to an SQL database in Go using the database/sql
package.