go语言mysql操作
Posted ycz0926
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go语言mysql操作相关的知识,希望对你有一定的参考价值。
package main import ( "database/sql" "encoding/base64" "fmt" "log" "math/rand" "os" "runtime" "strings" "sync" "sync/atomic" "time" _ "github.com/go-sql-driver/mysql" ) func randStr(n int) string { buf := make([]byte, n) rand.Read(buf) str := base64.StdEncoding.EncodeToString(buf) var b strings.Builder b.Grow(n) b.WriteString(str[:n]) return b.String() } func main() { // set cpu numbers runtime.GOMAXPROCS(8) // connect to mysql conn, err := sql.Open("mysql", "honbro:[email protected]/test2?charset=utf8") defer func() { _ = conn.Close() }() if err != nil { panic(err) } fmt.Println("mysql connect success") // insert data var wg sync.WaitGroup var count uint32 = 0 file, err := os.Create("count.txt") if err != nil { panic(err) } defer func() { _ = file.Close() }() wg.Add(1) go func() { defer wg.Done() for { time.Sleep(time.Second * 10) inserted := atomic.LoadUint32(&count) _, err := file.WriteString(fmt.Sprintf("%d ", inserted)) if err != nil { log.Println(err) } } }() for i := 0; i < 24; i++ { wg.Add(1) go func() { defer wg.Done() stmt, err := conn.Prepare("insert into battery(" + "datetime, tuopanmahao, xunibianhao, ceshidianya, ceshishijian, jueyuandianzu, shangwendu, xiawendu, " + "yali, reyagongwei, Azhengjierduiqidu1, Azhengjierduiqidu2, Afujierduiqidu3, Afujierduiqidu4, banci, " + "yuangonggonghao, shebeibianhao) values(" + "?, ‘M1800000B00028‘, ?, 200, 5, 66.3, 80.1, 90.1," + "‘65535‘, ‘A电芯热压1工位‘, 10, 52.24, 11.2, 53.56, ‘晚班‘," + " ‘JS001254‘, 2)") defer func() { _ = stmt.Close() }() if err != nil { panic(err) } for { inserted := atomic.LoadUint32(&count) if inserted == 10000000 { return } _, err := stmt.Exec(time.Now().Format("2006/01/02 15:04"), randStr(14)) if err != nil { log.Println(err) continue } atomic.AddUint32(&count, 1) } }() } wg.Wait() }
以上是关于go语言mysql操作的主要内容,如果未能解决你的问题,请参考以下文章