go get -u github.com/go-sql-driver/mysql
db, _ := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test")
err := db.Ping()
if err != nil {
fmt.Println("数据库连接失败")
}
defer db.Close()
单行查询
// 单行查询
sqlStr := "select id, name, age from user where id=?"
err = db.QueryRow(sqlStr, 2).Scan(&id, &name, &age)
if err != nil {
log.Fatal("error{}" ,err)
return
}
fmt.Printf("id:%d name:%s age:%d\n", id, name, age)
多行查询
// 多行查询
rows, err := db.Query("Select id,name,age from user")
for rows.Next() {
err := rows.Scan(&id, &name, &age)
if err != nil {
log.Fatal("error{}" ,err)
return
}
fmt.Printf("id:%d name:%s age:%d\n", id, name, age)
}
插入数据
// 插入数据
inSql := "insert into user(name, age) values (?,?)"
ret, err := db.Exec(inSql, "李四", 12)
if err != nil {
return
}
// 新插入数据的id
theID, err := ret.LastInsertId()
if err != nil {
log.Fatal("error{}" ,err)
return
}
fmt.Printf("插入的数据id是 %d \n", theID)
更新数据
// 更新数据
upSql := "update user set age=? where id = ?"
exec, err := db.Exec(upSql, 22, 1)
if err != nil {
log.Fatal("error{}" ,err)
return
}
// 更新了多少条数据
n, err := exec.RowsAffected()
if err != nil {
log.Fatal("error{}" ,err)
return
}
fmt.Printf("更新了 %d 行数据 \n", n)
删除数据
// 删除数据
delSql := "delete from user where id = ?"
result, err := db.Exec(delSql, 1)
if err != nil {
log.Fatal("error{}" ,err)
return
}
// 删除了多少条数据
affected, err := result.RowsAffected()
if err != nil {
log.Fatal("error{}" ,err)
return
}
fmt.Printf("删除了 %d 行数据 \n", affected)