// 参考:https://studygolang.com/articles/17444?fr=sidebar
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"log"
)
func checkErr(err error){
if err != nil{
panic(err)
}
}
var Db *sqlx.DB
func init() {
database, err := sqlx.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/book")
checkErr(err)
Db = database
return
}
func InsertTest(){
var sql string = " insert into users(id, name, email, password) values (?,?,?,?)"
_, err := Db.Exec(sql, 10, "zd", "xxx@qq.com", "zd123")
checkErr(err)
}
func update() {
_, err := Db.Exec("update users set name = ? where id =1", "test_update")
checkErr(err)
}
func deleteTest() {
_, err := Db.Exec("delete from users where id=10")
checkErr(err)
}
func SqlTest(){
sql := " select * from users where id =(?) "
//Db.Select(sql, )
res, err := Db.Query(sql, 1)
checkErr(err)
fmt.Println("11111111")
for res.Next() {
//fmt.Println(res)
//fmt.Printf("%v", )
var name string
var id int
var email string
var password string
if err := res.Scan(&id, &name, &email, &password); err != nil {
log.Fatal(err)
//}
}
fmt.Println("xxxxxxxxxxxxxx")
fmt.Printf("name:%s ,id:is %d
, %s, %s", name, id, email, password)
}
}
func main(){
SqlTest()
//InsertTest()
update()
deleteTest()
}