MySQL
MySQL是一个常用的关系型数据库管理系统,是用C和C++编写的。它的特点是速度快、稳定性好、易于使用。使用Golang连接MySQL数据库非常简单,只需导入相应的驱动程序和数据库包。 下面是一个示例代码,演示了如何连接MySQL数据库并执行查询操作:
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"fmt"
)
func main() {
db, err := sql.Open("mysql", "user:password@/dbname")
if err != nil {
panic(err.Error())
}
defer db.Close()
rows, err := db.Query("SELECT * FROM users")
if err != nil {
panic(err.Error())
}
defer rows.Close()
for rows.Next() {
var name string
var age int
err = rows.Scan(&name, &age)
if err != nil {
panic(err.Error())
}
fmt.Println(name, age)
}
}
PostgreSQL
PostgreSQL是一种功能强大的开源对象关系型数据库管理系统。它提供了许多高级特性,如事务、外键、触发器等。使用Golang连接PostgreSQL数据库与连接MySQL类似,只需引入相应的驱动程序和数据库包。 下面是一个示例代码,演示了如何连接PostgreSQL数据库并执行插入操作:
import (
"database/sql"
_ "github.com/lib/pq"
"fmt"
)
func main() {
db, err := sql.Open("postgres", "host=pgdb user=user password=password dbname=mydatabase port=5432 sslmode=disable")
if err != nil {
panic(err.Error())
}
defer db.Close()
_, err = db.Exec("INSERT INTO users (name, age) VALUES ($1, $2)", "John", 30)
if err != nil {
panic(err.Error())
}
fmt.Println("Insert success!")
}
MongoDB
MongoDB是一个开源的文档型数据库管理系统,以其灵活的数据模型而闻名。使用Golang连接MongoDB数据库需要安装相应的驱动程序。 下面是一个示例代码,演示了如何连接MongoDB数据库并执行更新操作:
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type User struct {
Name string
Age int
}
func main() {
ctx := context.TODO()
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
panic(err.Error())
}
defer client.Disconnect(ctx)
collection := client.Database("test").Collection("users")
filter := bson.M{"name": "John"}
update := bson.M{"$set": bson.M{"age": 35}}
_, err = collection.UpdateOne(ctx, filter, update)
if err != nil {
panic(err.Error())
}
fmt.Println("Update success!")
}
以上是三个常见的Golang数据库案例,分别介绍了如何连接MySQL、PostgreSQL和MongoDB,并执行一些基本的数据库操作。通过这些案例,可以帮助开发者快速上手使用Golang进行数据库开发。
总结来说,Golang提供了丰富的数据库驱动程序和库,使得连接和操作各种数据库变得非常简单。通过简洁、高效的代码,开发者可以更专注于业务逻辑的实现,提高开发效率。