Golang mysql

时间:2024-01-16 16:45:08

还是那句话,服务器嘛,每个数据库支持,那成啥子啦嘛!

好吧,今天,就让Go能连上数据库,当然是之前给你铺垫的MySql的啦,哈哈

一。安装第三方包支持访问mysql数据库

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

二。写一个主程序

//database.go

package main

import (

"database/sql"

"fmt"

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

)

func checkErr(err error) {

if err != nil {

panic(err)

}

}

func main() {

//打开数据库mytest

fmt.Println("open the database, mytest")

db, err := sql.Open("mysql", "root:11111111@tcp(127.0.0.1:3306)/mytest?charset=utf8")

checkErr(err)

//插入数据

fmt.Println("insert data info into table, userinfo")

stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")

checkErr(err)

res, err := stmt.Exec("Test", "people", "2017-10-27")

checkErr(err)

//记录ID

fmt.Println("record the ID of affecting item")

id, err := res.LastInsertId()

checkErr(err)

fmt.Println(id)

  //更新数据

fmt.Println("update data info where id was conform to be affected")

stmt, err = db.Prepare("update userinfo set username=? where uid=?")

checkErr(err)

res, err = stmt.Exec("man", id)

checkErr(err)

affect, err := res.RowsAffected()

checkErr(err)

fmt.Println(affect)

//查询数据

fmt.Println("query data info from table, userinfo")

rows, err := db.Query("SELECT * FROM userinfo")

checkErr(err)

fmt.Println("iterator data info to show")

for rows.Next() {

var uid int

var username string

var department string

var created string

err = rows.Scan(&uid, &username, &department, &created)

checkErr(err)

fmt.Println(uid)

fmt.Println(username)

fmt.Println(department)

fmt.Println(created)

}

  //删除数据

stmt, err = db.Prepare("delete from userinfo where uid=?")

checkErr(err)

res, err = stmt.Exec(id)

checkErr(err)

affect, err = res.RowsAffected()

checkErr(err)

fmt.Println(affect)

//关闭数据库mytest

db.Close()

}

三。建立数据库和表

mysql>create database mytest;

mysql>use mytest;

mysql> CREATE TABLE `userinfo` (

->     `uid` INT(10) NOT NULL AUTO_INCREMENT,

->     `username` VARCHAR(64) NULL DEFAULT NULL,

->     `departname` VARCHAR(64) NULL DEFAULT NULL,

->     `created` DATE NULL DEFAULT NULL,

->     PRIMARY KEY (`uid`)

-> );

四。结果

# ./database

open the database, mytest

insert data info into table, userinfo

record the ID of affecting item

4

update data info where id was conform to be affected

1

query data info from table, userinfo

iterator data info to show

4

man

people

2017-10-27

1

Finally:

哈哈,数据库都给你配上了,诸位还不开始Go(滚)吗?

哈哈哈哈哈哈哈