[go] Go 언어를 이용한 데이터베이스 연동하기
본 블로그에서는 Go 언어를 사용하여 데이터베이스를 연동하는 방법에 대해 알아보겠습니다.
목차
1. Go와 데이터베이스
Go 언어는 표준 라이브러리에 database/sql
패키지를 포함하고 있어서 다양한 데이터베이스와의 연동을 지원합니다. 이 패키지는 데이터베이스와 상호 작용하는 데 필요한 기본적인 도구와 기능들을 제공합니다.
2. MySQL 데이터베이스 연동
Go 언어로 MySQL 데이터베이스를 연동하는 방법은 다음과 같습니다.
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
if err != nil {
panic(err.Error())
}
defer db.Close()
}
3. PostgreSQL 데이터베이스 연동
Go 언어에서 PostgreSQL 데이터베이스를 연동하는 방법은 아래와 같습니다.
import (
"database/sql"
_ "github.com/lib/pq"
)
func main() {
db, err := sql.Open("postgres", "user=your-user dbname=your-db sslmode=disable")
if err != nil {
panic(err.Error())
}
defer db.Close()
}
4. MongoDB 데이터베이스 연동
Go 언어에서 MongoDB 데이터베이스를 연동하는 방법은 다음과 같습니다.
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
panic(err.Error())
}
defer client.Disconnect(context.Background())
}
5. 마무리
본 블로그에서는 Go 언어와 다양한 데이터베이스를 연동하는 방법에 대해 간략히 알아보았습니다. Go 언어의 강력한 기능을 활용하여 데이터베이스와의 연동을 효과적으로 수행할 수 있습니다. 추가로 자세한 내용은 공식 문서를 참고하시기 바랍니다.