Go语言-MySQL

数据库信息

创建数据库:CREATE DATABASE go-test-01 DEFAULT CHARACTER SET utf8;

创建表:

create table table1(
id int primary key auto_increment,
name varchar(20) not null,
addr varchar(20) 
);

Go实例代码

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func insert(db *sql.DB) {
    stmt, err := db.Prepare("insert into table1(name, addr) values(?, ?)")
    defer stmt.Close()
    if err != nil {
        fmt.Println("Insert table Error =", err)
    }
    stmt.Exec("Tom", "Beijing")
}

func main() {
    db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/go_test_01?charset=utf8")
    defer db.Close()
    if err != nil {
        fmt.Println("Open database Error =", err)
    }
    insert(db)
}

查询多行

func Uids(tid int64) ([]int64, error) {
        db, err := sql.Open("mysql", g.Config().Uic.Addr)
        if err != nil {
                return []int64{}, err
        }
        defer db.Close()
        err = db.Ping()
        if err != nil {
                return []int64{}, err
        }

        s := fmt.Sprintf("SELECT uid FROM rel_team_user WHERE tid = %d", tid)
        rows, err := db.Query(s)
        if err != nil {
                return []int64{}, err
        }
        arr := []int64{}
        var uid int64
        for rows.Next() {
                err := rows.Scan(&uid)
                if err != nil {
                        return []int64{}, err
                }
                arr = append(arr, uid)
        }
        return arr, err
}

查询一行

func SelectTeamById(id int64) *Team {
if id < = 0 { return nil } db, err := sql.Open("mysql", g.Config().Uic.Addr) if err != nil { return nil } defer db.Close() err = db.Ping() if err != nil { return nil } var obj Team s := fmt.Sprintf("SELECT name, resume, creator FROM team WHERE id = %d", id) var name string var resume string var creator int64 errQueryRow := db.QueryRow(s).Scan(&name, &resume, &creator) if errQueryRow != nil { return nil } obj.Id = id obj.Name = name obj.Resume = resume obj.Creator = creator return &obj } [/go]

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部