46 lines
927 B
Go
46 lines
927 B
Go
package goroutine
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"github.com/google/uuid"
|
|
"math/rand"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
func Datawrite(db *sql.DB, donetitle chan struct{}) {
|
|
timetick := time.Tick(1 * time.Second)
|
|
rand.Seed(time.Now().UnixNano())
|
|
|
|
for {
|
|
select {
|
|
case <-timetick:
|
|
uid, error := uuid.NewRandom()
|
|
if error != nil {
|
|
panic(error)
|
|
}
|
|
tx, err := db.Begin()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
fmt.Println("开始事务")
|
|
_, err = tx.Exec(`insert INTO article (uid,content,author,age) values (?,?,?,?)`, uid, "123", "用户"+strconv.Itoa(rand.Intn(1000)), rand.Intn(40)+60)
|
|
if err != nil {
|
|
if rbErr := tx.Rollback(); rbErr != nil {
|
|
panic("回滚失败: " + rbErr.Error())
|
|
}
|
|
panic("插入失败: " + err.Error()) // 明确错误类型
|
|
}
|
|
err = tx.Commit()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
fmt.Println("插入数据成功")
|
|
case <-donetitle:
|
|
return
|
|
}
|
|
}
|
|
|
|
}
|