mysql prepare us finished
parent
65a48c079f
commit
ef2f287ae9
|
@ -1,7 +1,9 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<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/sql_prepare.go" dialect="GenericSQL" />
|
||||
<file url="PROJECT" dialect="GenericSQL" />
|
||||
</component>
|
||||
</project>
|
|
@ -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()
|
||||
}
|
Loading…
Reference in New Issue