1. 程式人生 > >golang操作MySQL

golang操作MySQL

package main

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

func main()  {
	db,err:=sql.Open("mysql","root:@(127.0.0.1:3306)/db181030") //set parameters
	if err!=nil {
		fmt.Println(err)
		return
	}
	defer db.Close()
	err=db.Ping() //connect
	if err!=nil {
		fmt.Println(err)
		return
	}
	
	re,err:=db.Exec("INSERT INTO `t_person` (`name`) VALUES ('aa')")
	if err!=nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%T\n",re)
	n,err:=re.RowsAffected()
	if err!=nil {
		fmt.Println(err)
		return
	}
	fmt.Println("affected rows ",n)
	n,err=re.LastInsertId()
	if err!=nil {
		fmt.Println(err)
		return
	}
	fmt.Println("last insert id ",n)
	
	persons:=[2][1]string{{"bb"},{"cc"}}
	stmt,err:=db.Prepare("INSERT INTO `t_person` (`name`) VALUES (?)")
	if err!=nil {
		fmt.Println(err)
		return
	}
	for _,v:=range persons{
		re,err:=stmt.Exec(v[0])
		if err!=nil {
			fmt.Println(err)
			return
		}
		n,err:=re.LastInsertId()
		if err!=nil {
			fmt.Println(err)
			return
		}
		fmt.Println("last insert id",n)
		n,err=re.RowsAffected()
		if err!=nil {
			fmt.Println(err)
			return
		}
		fmt.Println("affected rows",n)
	}
	
	/*rows:=db.QueryRow("SELECT * FROM `t_person` WHERE `id`=3")
	var id,name string
	rows.Scan(&id,&name)
	fmt.Println(id,name)*/
	rows,err:=db.Query("SELECT * FROM `t_person`")
	if err!=nil {
		fmt.Println(err)
		return
	}
	var id,name string
	for rows.Next() {
		rows.Scan(&id,&name)
		fmt.Printf("%d %d\n",id,name)
	}
}