package main
import (
"database/sql"
"fmt"
//自身没有直接操作的库,所以使用的常用的第三方库
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/test?charset=utf8")
checkErr(err)
fmt.Println("数据库已经连接")
//插入数据
stmt, err := db.Prepare("INSERT user SET name=?,age=?")
checkErr(err)
res, err := stmt.Exec("xiaoming", "12")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Printf("插入成功,ID为:%d\n", id)
stmt, err = db.Prepare("update user set name=? where id=?")
checkErr(err)
res, err = stmt.Exec("xiaowang", id)
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println(affect)
rows, err := db.Query("SELECT * FROM user")
checkErr(err)
for rows.Next() {
var id int
var name string
var age int
err = rows.Scan(&id, &name, &age)
checkErr(err)
fmt.Println(id)
fmt.Println(name)
fmt.Println(age)
}
//删除数据
stmt, err = db.Prepare("delete from userinfo where uid=?")
checkErr(err)
res, err = stmt.Exec(id)
checkErr(err)
affect, err = res.RowsAffected()
checkErr(err)
fmt.Println(affect)
db.Close()
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
import (
"database/sql"
"fmt"
//自身没有直接操作的库,所以使用的常用的第三方库
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "root:root@tcp(localhost:3306)/test?charset=utf8")
checkErr(err)
fmt.Println("数据库已经连接")
//插入数据
stmt, err := db.Prepare("INSERT user SET name=?,age=?")
checkErr(err)
res, err := stmt.Exec("xiaoming", "12")
checkErr(err)
id, err := res.LastInsertId()
checkErr(err)
fmt.Printf("插入成功,ID为:%d\n", id)
stmt, err = db.Prepare("update user set name=? where id=?")
checkErr(err)
res, err = stmt.Exec("xiaowang", id)
checkErr(err)
affect, err := res.RowsAffected()
checkErr(err)
fmt.Println(affect)
rows, err := db.Query("SELECT * FROM user")
checkErr(err)
for rows.Next() {
var id int
var name string
var age int
err = rows.Scan(&id, &name, &age)
checkErr(err)
fmt.Println(id)
fmt.Println(name)
fmt.Println(age)
}
//删除数据
stmt, err = db.Prepare("delete from userinfo where uid=?")
checkErr(err)
res, err = stmt.Exec(id)
checkErr(err)
affect, err = res.RowsAffected()
checkErr(err)
fmt.Println(affect)
db.Close()
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}