【golang完全指南】go 连接mysql数据库,并且创建初始化数据


title: go 连接mysql数据库,并且创建初始化数据

依赖
import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

连接数据库

    db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/stark")
    if err != nil {
        fmt.Print(err.Error())
    }
    defer db.Close()

测试数据库是否可以连接成功

    err = db.Ping()
    if err != nil {
        fmt.Print(err.Error())
    }

创建初始数据结构

    stmt, err := db.Prepare("CREATE TABLE user (id int NOT NULL AUTO_INCREMENT, name varchar(40), age varchar(40), PRIMARY KEY (id));")
    if err != nil {
        fmt.Println(err.Error())
    }
    _, err = stmt.Exec()
    if err != nil {
        fmt.Print(err.Error())
    } else {
        fmt.Printf("User Table successfully ....")
    }

源码

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/stark")
    if err != nil {
        fmt.Print(err.Error())
    }
    defer db.Close()
    // make sure connection is available
    err = db.Ping()
    if err != nil {
        fmt.Print(err.Error())
    }

    stmt, err := db.Prepare("CREATE TABLE user (id int NOT NULL AUTO_INCREMENT, name int(11), age varchar(40), PRIMARY KEY (id));")
    if err != nil {
        fmt.Println(err.Error())
    }
    _, err = stmt.Exec()
    if err != nil {
        fmt.Print(err.Error())
    } else {
        fmt.Printf("User Table successfully ....")
    }
}

你可能感兴趣的:(golang)