📜  如何在 MySQL 中使用 Go?

📅  最后修改于: 2021-10-24 14:04:02             🧑  作者: Mango

MySQL 是一种基于结构化查询语言 (SQL) 的开源关系数据库管理系统。它是一种将数据组织成一个或多个数据相互关联的表的关系数据库。

数据库驱动程序:数据库驱动程序实现了数据库连接的协议。驱动程序就像连接到特定数据库的通用接口的适配器。

初始设置:

启动 MySQL 服务器并使用以下命令安装 go MySQL 驱动程序。

go get -u github.com/go-sql-driver/mysql

创建数据库对象:

使用 sql.Open 创建一个数据库对象。没有与 MySQL 建立连接,它只创建一个以后可以使用的数据库对象。

db, err := sql.Open("mysql", ":@tcp(127.0.0.1:3306)/")

如果不在默认端口上使用 MySQL,则替换 3306。

Go
package main
 
import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)
 
func main() {
     
    // create a database object which can be used
    // to connect with database.
    db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
     
    // handle error, if any.
    if err != nil {
        panic(err)
    }
     
    // Now its  time to connect with oru database,
    // database object has a method Ping.
    // Ping returns error, if unable connect to database.
    err = db.Ping()
     
    // handle error
    if err != nil {
        panic(err)
    }
     
    fmt.Print("Pong\n")
     
    // database object has  a method Close,
    // which is used to free the resource.
    // Free the resource when the function
    // is returned.
    defer db.Close()
}


Go
package main
 
import (
    "database/sql"
    "fmt"
 
    _ "github.com/go-sql-driver/mysql"
)
 
func main() {
 
    // create a database object which can be used
    // to connect with database.
    db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
     
    // handle error, if any.
    if err != nil {
        panic(err)
    }
     
    //  database object has a method called Exec,
    // it executes a database query, but it does
    // not return any row as result.
    // Here we create a database table with a SQL query.
    _, err = db.Exec("CREATE TABLE user(id INT NOT NULL, name VARCHAR(20),
                     PRIMARY KEY (ID));")
     
    // handle error
    if err != nil {
        panic(err)
    }
     
    fmt.Print("Successfully Created\n")
     
    // database object has  a method Close,
    // which is used to free the resource.
    // Free the resource when the function
    // is returned.
    defer db.Close()
}


Go
package main
 
import (
    "database/sql"
    "fmt"
 
    _ "github.com/go-sql-driver/mysql"
)
 
func main() {
 
    // create a database object which can be used
    // to connect with database.
    db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
     
    // handle error, if any.
    if err != nil {
        panic(err)
    }
     
    // database objec has a method called Query,
    // It can execute a SQL query and return rows
    // as result. Here we insert a row into  the  table,
    // no row returned as result for this operation.
    _, err = db.Query("INSERT INTO user VALUES(1,'sam')")
     
    // handle error
    if err != nil {
        panic(err)
    }
     
    fmt.Print("Successfully  Inserted\n")
 
    // database object has  a method Close,
    // which is used to free the resource.
    // Free the resource when the function
    // is returned.
    defer db.Close()
}


Go
package main
 
import (
    "database/sql"
    "fmt"
 
    _ "github.com/go-sql-driver/mysql"
)
 
func main() {
     
    // create a database object which can be
    // used to connect with database.
    db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
     
    // handle error, if any.
    if err != nil {
        panic(err)
    }
     
    // Here a SQL query is used to return all
    // the data from the table user.
    result, err := db.Query("SELECT * FROM user")
     
    // handle error
    if err != nil {
        panic(err)
    }
     
    // the result object has a method called Next,
    // which is used to iterate throug all returned rows.
    for result.Next() {
         
        var id int
        var name string
         
        // The result object provided Scan  method
        // to read row data, Scan returns error,
        // if any. Here we read id and name returned.
        err = result.Scan(&id, &name)
         
        // handle error
        if err != nil {
            panic(err)
        }
         
        fmt.Printf("Id: %d Name: %s\n", id, name)
    }
 
    // database object has  a method Close,
    // which is used to free the resource.
    // Free the resource when the function
    // is returned.
    defer db.Close()
}


输出:

图 1.1

执行数据库查询:可以使用 Exec() 和 Query() 完成数据库查询。

1.使用 SQL 查询和 Exec() 创建数据库表。

package main
 
import (
    "database/sql"
    "fmt"
 
    _ "github.com/go-sql-driver/mysql"
)
 
func main() {
 
    // create a database object which can be used
    // to connect with database.
    db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
     
    // handle error, if any.
    if err != nil {
        panic(err)
    }
     
    //  database object has a method called Exec,
    // it executes a database query, but it does
    // not return any row as result.
    // Here we create a database table with a SQL query.
    _, err = db.Exec("CREATE TABLE user(id INT NOT NULL, name VARCHAR(20),
                     PRIMARY KEY (ID));")
     
    // handle error
    if err != nil {
        panic(err)
    }
     
    fmt.Print("Successfully Created\n")
     
    // database object has  a method Close,
    // which is used to free the resource.
    // Free the resource when the function
    // is returned.
    defer db.Close()
}

输出:

2.使用 Query() 中的 SQL 查询向数据库表中插入一行。

package main
 
import (
    "database/sql"
    "fmt"
 
    _ "github.com/go-sql-driver/mysql"
)
 
func main() {
 
    // create a database object which can be used
    // to connect with database.
    db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
     
    // handle error, if any.
    if err != nil {
        panic(err)
    }
     
    // database objec has a method called Query,
    // It can execute a SQL query and return rows
    // as result. Here we insert a row into  the  table,
    // no row returned as result for this operation.
    _, err = db.Query("INSERT INTO user VALUES(1,'sam')")
     
    // handle error
    if err != nil {
        panic(err)
    }
     
    fmt.Print("Successfully  Inserted\n")
 
    // database object has  a method Close,
    // which is used to free the resource.
    // Free the resource when the function
    // is returned.
    defer db.Close()
}

输出:

3.在 Query() 中使用 SQL 查询返回用户表中的所有行。

package main
 
import (
    "database/sql"
    "fmt"
 
    _ "github.com/go-sql-driver/mysql"
)
 
func main() {
     
    // create a database object which can be
    // used to connect with database.
    db, err := sql.Open("mysql", "root:passwd@tcp(0.0.0.0:3306)/user")
     
    // handle error, if any.
    if err != nil {
        panic(err)
    }
     
    // Here a SQL query is used to return all
    // the data from the table user.
    result, err := db.Query("SELECT * FROM user")
     
    // handle error
    if err != nil {
        panic(err)
    }
     
    // the result object has a method called Next,
    // which is used to iterate throug all returned rows.
    for result.Next() {
         
        var id int
        var name string
         
        // The result object provided Scan  method
        // to read row data, Scan returns error,
        // if any. Here we read id and name returned.
        err = result.Scan(&id, &name)
         
        // handle error
        if err != nil {
            panic(err)
        }
         
        fmt.Printf("Id: %d Name: %s\n", id, name)
    }
 
    // database object has  a method Close,
    // which is used to free the resource.
    // Free the resource when the function
    // is returned.
    defer db.Close()
}

输出: