mysql prepare us finished

main
Your Name 2024-07-19 01:01:45 +08:00
parent 65a48c079f
commit ef2f287ae9
2 changed files with 80 additions and 1 deletions

View File

@ -1,7 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="SqlDialectMappings"> <component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/mysql/mysql_insert.go" dialect="GenericSQL" /> <file url="file://$PROJECT_DIR$/mysql/mysql_insert_update_delete.go" dialect="GenericSQL" />
<file url="file://$PROJECT_DIR$/mysql/mysql_rowquery.go" dialect="GenericSQL" /> <file url="file://$PROJECT_DIR$/mysql/mysql_rowquery.go" dialect="GenericSQL" />
<file url="file://$PROJECT_DIR$/mysql/sql_prepare.go" dialect="GenericSQL" />
<file url="PROJECT" dialect="GenericSQL" />
</component> </component>
</project> </project>

77
mysql/sql_prepare.go Normal file
View File

@ -0,0 +1,77 @@
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
)
var dataB *sql.DB
func initDataB() (err error) {
dataB, err = sql.Open("mysql", "root:123456@tcp(43.143.245.135:3306)/wangaodev")
if err != nil {
log.Println(err)
return err
}
err = dataB.Ping()
if err != nil {
log.Println(err)
return err
}
log.Println("Successfully connected to mysql")
dataB.SetMaxOpenConns(10)
dataB.SetMaxIdleConns(5)
return nil
}
type newUser struct {
name string
level string
status int
}
func generateNewUser(name, level string, status int) *newUser {
return &newUser{
name: name,
level: level,
status: status,
}
}
// 预处理方式插入多条数据
func prepareInsert() {
sqlStr := `insert into user (name,level,status) values (?,?,?)`
stmt, err := dataB.Prepare(sqlStr)
if err != nil {
log.Fatal("prepare failed:", err)
}
defer stmt.Close()
//后续只需要拿到stmt去执行一些操作
userData := []newUser{
{name: "Alice", level: "中级", status: 1},
{name: "Bob", level: "高级", status: 2},
{name: "Charlie", level: "初级", status: 0},
}
//循环结构体切片执行
var sum = 0
for _, v := range userData {
ret, err := stmt.Exec(v.name, v.level, v.status)
if err != nil {
return
}
n, _ := ret.RowsAffected()
sum = sum + int(n)
}
fmt.Printf("%v rows has been affected", sum)
}
func main() {
err := initDataB()
if err != nil {
return
}
prepareInsert()
}