Go 操作数据库尝鲜
以下代码为go链接mysql操作mysql的部分代码
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
type User struct{
ID int64
Name string
Age int8
}
var db *sql.DB
func InitDB() (err error) {
dbh := "bbsgo:bbsgo1234!@tcp(192.168.0.155:3306)/bbsgo_db"
db, err = sql.Open("mysql", dbh)
if err != nil {
return err
}
err = db.Ping()
if err != nil {
return err
}
return nil
}
func CreateTable() {
sqlStr := "create table IF NOT EXISTS sqlTest1 (ID int AUTO_INCREMENT PRIMARY KEY, Name varchar(12) " +
"NOT NULL UNIQUE, AGE TINYINT NOT NULL)"
ret, err := db.Exec(sqlStr)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(ret)
fmt.Println(ret)
r, err := ret.RowsAffected()
fmt.Println(r)
fmt.Println(err)
}
func InsertData() {
sqlStr := "insert into sqlTest(Name, AGE) value(?, ?)"
ret, err := db.Exec(sqlStr, "asd", 1)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(ret)
fmt.Println(ret)
r, err := ret.RowsAffected()
fmt.Println(r)
fmt.Println(err)
}
func Select() {
sqlStr := "SELECT * FROM sqlTest;"
var uList []*User
var u User
ret, err := db.Query(sqlStr)
if err != nil {
fmt.Println(err)
return
}
defer ret.Close()
fmt.Println(ret, *ret)
for ret.Next() {
err := ret.Scan(&u.ID, &u.Name, &u.Age)
if err != nil {
fmt.Println(err)
} else {
uList = append(uList, &u)
}
}
fmt.Println(uList)
fmt.Println(uList[0])
}
func main() {
err := InitDB()
if err != nil {
fmt.Println(err)
}
//CreateTable()
//InsertData()
Select()
}